Dictionary meaning of Prototype: A first or preliminary version of a device or vehicle from which other forms are developed.
Java prototype design pattern comes under the Creational Design Pattern category and it is used in the situations when a new object creation is costly.
Java prototype design pattern states that if a new object creation is costly than clone original object and then modify it, instead of creating a new object.
Let’s, we have a customer object which is loaded from database and after loading we have to modify its data multiple times. In such situations we have to clone that object instead of creating a new object and loading all data from database again.
Example
Customers.java
package com.w3schools; import java.util.ArrayList; import java.util.List; public class Customers implements Cloneable{ private List<String> customerList; public Customers(){ customerList = new ArrayList<String>(); } public Customers(List<String> list){ this.customerList=list; } public void loadDataFromDB(){ //Read all customers from DB customerList.add("Bharat"); customerList.add("Sahdev"); customerList.add("Richi"); customerList.add("Jai"); customerList.add("Bharti"); customerList.add("Saveta"); customerList.add("Deepika"); } public List<String> getCustomerList() { return customerList; } @Override public Object clone() throws CloneNotSupportedException{ List<String> temp = new ArrayList<String>(); for(String string : this.getCustomerList()){ temp.add(string); } return new Customers(temp); } } |
PrototypePatternTest.java
package com.w3schools; import java.util.List; public class PrototypePatternTest { public static void main(String args[]){ try { Customers customers = new Customers(); customers.loadDataFromDB(); Customers customers1 = (Customers) customers.clone(); Customers customers2 = (Customers) customers.clone(); List<String> customersList1 = customers1.getCustomerList(); customersList1.add("Vivek"); List<String> customersList2 = customers2.getCustomerList(); customersList2.remove("Deepika"); System.out.println("customers List elements: "+customers.getCustomerList()); System.out.println("customers1 List elements: "+customersList1); System.out.println("customers2 List elements: "+customersList2); } catch (CloneNotSupportedException e) { e.printStackTrace(); } } } |
Output
customers List elements: [Bharat, Sahdev, Richi, Jai, Bharti, Saveta, Deepika] customers1 List elements: [Bharat, Sahdev, Richi, Jai, Bharti, Saveta, Deepika, Vivek] customers2 List elements: [Bharat, Sahdev, Richi, Jai, Bharti, Saveta] |