class Book {
private String author;
private String title;
public Book(String author, String title){
this.author = author;
this.title = title;
}
// getter, setter
public String toString() {
return "("+author + "," + title; + ")"
}
}
class BookShelf implements Colneable{
private ArrayList<Book> shelf;
public BookShelf() {
shelf = new ArrayList<Book>();
}
public void addBook(Book book) {
shelf.add(book);
}
// getter, setter
@Override
protected Object clone() throws CloneNotSupportedException {
// return super.clone(); // 얕은 복사
BookShelf another = new BookShelf(); // 깊은 복사
for(Book book : shelf){
another.addBook(new Book(book.getAuthor(), book.getTitle())));
}
return antoher;
}
public String toString() {
return shelf.toString();
}
}
public class PrototypeTest {
public static void main(String[] args) throws CloneNotSupportedException{
BookShelf bookShelf = new BookShelf();
bookShelf.addBook(new Book("태백산맥","조정래"));
bookShelf.addBook(new Book("밥1","밥1"));
bookShelf.addBook(new Book("bob1","bob1"));
System.out.println(bookShelf);
// [(조정래,태백산맥),(밥1,밥1),(bob1,bob1)]
BookShelf another = (BookShelf)bookShelf.clone();
System.out.println(another)
// [(조정래,태백산맥),(밥1,밥1),(bob1,bob1)]
bookShelf.getShelf().get(0).setAuthor("조정래");
bookShelf.getShelf().get(0).setTitle("한강");
System.out.println(bookShelf);
System.out.println(another);
// [(조정래,한강),(밥1,밥1),(bob1,bob1)]
// [(조정래,한강),(밥1,밥1),(bob1,bob1)]
// 얕은 복사가 됨
// 깊은 복사 하면
// [(조정래,한강),(밥1,밥1),(bob1,bob1)]
// [(조정래,태백산맥),(밥1,밥1),(bob1,bob1)]
}
}
댓글남기기