Sunday, February 13, 2022

Prototype design pattern

 Prototype design pattern is a creational design pattern. It is used when object creation is costly and we want to use same object . So we can create prototype of the current object and can use it . let's see the example,

Book class-

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 + "]";

}

//BookShop class--

public class BookShop implements Cloneable {// must implement cloneable interface to copy of the                                                                                      object

private String shopName;

private List<Book> books;

public BookShop(String shopName) {

super();

this.shopName = shopName;

books = new ArrayList<Book>();

}

public String getShopName() {

return shopName;

}

public void setShopName(String shopName) {

this.shopName = shopName;

}

public List<Book> getBooks() {

return books;

}

public void setBooks(List<Book> books) {

this.books = books;

}

public void loadBooks() {

for (int i = 0; i < 10; i++) {

Book book = new Book(i, "book" + i);

books.add(book);

}

}

@Override

protected Object clone() throws CloneNotSupportedException { //should override clone() method

return super.clone();

}

@Override

public String toString() {

return "BookShop [shopName=" + shopName + ", books=" + books + "]";

}

}

//Main class

public class MainApp {

public static void main(String[] args) {

BookShop shop1 = new BookShop("shop 1");

shop1.loadBooks();

System.out.println(shop1);

try {

BookShop shop2 =(BookShop) shop1.clone();

shop2.setShopName("shop2");

System.out.println(shop2);

} catch (CloneNotSupportedException e) {

e.printStackTrace();

}

}

}



No comments:

Post a Comment

Fluent interface pattern

 public class UserConfigurationManager {     private String userName;     private String password;     private UserConfigurationManager() { ...