Prototype Design Pattern in java

  • When you want to create an object factory pattern is the best way but there are scenarios where you want to create object in a certain way for example
  • If you create an object which fetches the values from database and it takes a bit of time to create that object.
  • So the next time you want to create the same object you will not make the database call instead you will fetches the initial object from the 1st object that was created(basically a clone), this is called as Prototype design pattern.

In the below example, we are going to create an object and deep clone it so that new and the old variable does not have the same object.

Things to note while cloning :

  • Clone method is present in Object class but its access modifiers is protected hence you cannot write obj.clone() directly
  • We need to implement cloneable interface on the class which we are going to clone.
  • We need to override the clone method so that we can perform deep cloning

public class Book {
	private int bid;
	private String bname;

	public Book(int bid, String bname) {
		super();
		this.bid = bid;
		this.bname = bname;
	}

	public int getBid() {
		return bid;
	}

	public void setBid(int bid) {
		this.bid = bid;
	}

	public String getBname() {
		return bname;
	}

	public void setBname(String bname) {
		this.bname = bname;
	}

	@Override
	public String toString() {
		return "Book [bid=" + bid + ", bname=" + bname + "]";
	}
}
public class BookShop implements Cloneable{
	
	private String storeName;
	private List<Book> books = new ArrayList<>();

	public String getStoreName() {
		return storeName;
	}

	public void setStoreName(String storeName) {
		this.storeName = storeName;
	}

	public List<Book> getBooks() {
		return books;
	}

	public void setBooks(List<Book> books) {
		this.books = books;
	}

	@Override
	public String toString() {
		return "BookShop [storeName=" + storeName + ", books=" + books + "]";
	}
	
	public void loadData() {
		for(int i=1; i<5; i++) {
			Book b = new Book(i,"Book"+i);
			books.add(b);
		}
	}

	@Override
	protected BookShop clone() throws CloneNotSupportedException {
		BookShop bookShop = new BookShop();
		for(Book b : this.getBooks()) {
			bookShop.getBooks().add(b);
		}
		return bookShop;
	}

}

public class PrototypeDemo {
	public static void main(String[] args) throws CloneNotSupportedException {
		BookShop bookShop1 = new BookShop();
		bookShop1.setStoreName("A1 Book store");
		bookShop1.loadData();
		BookShop bookShop2 = (BookShop)bookShop1.clone();
		bookShop2.setStoreName("A2 Book store");
		bookShop1.getBooks().remove(2);
		System.out.println(bookShop1);
		System.out.println(bookShop2);
	}
}

Leave a Comment