디자인패턴

Prototype 패턴

끄적끄적 2022. 4. 20. 20:57

프로토타입을 복사하여 인스턴스를 생성

class BookShelf implements Cloneable{
    private ArrayList<Book> shelf;

    public BookShelf(){
        shelf = new ArrayList<Book>();
    }

    public void addBook(Book book){
        shelf.add(book);
    }

    public ArrayList<Book> getShelf() {
        return shelf;
    }

    public void setShelf(ArrayList<Book> shelf) {
        this.shelf = shelf;
    }

    @Override
    public String toString() {
        return "BookShelf{" +
                "shelf=" + shelf.toString() +
                '}';
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        BookShelf another = new BookShelf();

        for (Book book : shelf) {
            another.addBook(new Book(book.getAuthor(), book.getTitle()));
        }
        return another;
    }
}

위 처럼 Clone() 메서드를 Override 하고, clone()해서 사용할 수 있다.

public class PrototypeTest {

    public static void main(String[] args) throws CloneNotSupportedException {
        BookShelf bookShelf = new BookShelf();
        bookShelf.addBook(new Book("taekyung", "Harry Porter"));
        bookShelf.addBook(new Book("seaking", "Ring of King"));
        bookShelf.addBook(new Book("make", "Spider Man"));
        System.out.println("bookShelf = " + bookShelf);

        BookShelf another = (BookShelf) bookShelf.clone();
        System.out.println("another = " + another);

        bookShelf.getShelf().get(0).setAuthor("tom");
        bookShelf.getShelf().get(0).setTitle("Dragon");
        System.out.println("bookShelf = " + bookShelf);
        System.out.println("another = " + another);
    }
}
반응형