Recent Posts

Monday, 3 October 2016

Prototype Design Pattern Tutorial


Prototype Design Pattern 
     This design pattern is used when the Object creation is a costly affair and requires a lot of time and resources and you have a similar object already existing. This design pattern provides a mechanism to copy the original object to a new object and then modify it according to our needs. Prototype design pattern uses java cloning to copy the object.

Example
     Suppose we have an Object that loads data from database. Now we need to modify this data in our program multiple times, so it’s not a good idea to create the Object using new keyword and load all the data again from database. The better approach would be to clone the existing object into a new object and then do the data manipulation.
package com.ashok.designpatterns.prototype;

import java.util.ArrayList;
import java.util.List;

public class Employees implements Cloneable {

   private List<String> empList;

   public Employees() {
      empList = new ArrayList<String>();
   }

   public Employees(List<String> list) {
      this.empList = list;
   }

   public void loadData() {
      // read all employees from database and put into the list
      empList.add("Ashok");
      empList.add("Vinod");
      empList.add("Dillesh");
      empList.add("Latha");
   }

   public List<String> getEmpList() {
      return empList;
   }

   @Override
   public Object clone() throws CloneNotSupportedException {
      List<String> temp = new ArrayList<String>();
      for (String s : this.getEmpList()) {
         temp.add(s);
      }
      return new Employees(temp);
   }
}
     Now the prototype design pattern example test program that will show the benefit of prototype pattern.
package com.ashok.designpatterns.prototype;

import java.util.List;

import com.ashok.designpatterns.prototype.Employees;

public class MyPrototypePatternTest {

   public static void main(String[] args) throws CloneNotSupportedException {
      Employees emps = new Employees();
      emps.loadData();

      Employees emps1 = (Employees) emps.clone();
      Employees emps2 = (Employees) emps.clone();
      List<String> list = emps1.getEmpList();
      list.add("Janaki");
      List<String> list1 = emps2.getEmpList();
      list1.remove("Dillesh");

      System.out.println("emps List  : " + emps.getEmpList());
      System.out.println("emps1 List : " + list);
      System.out.println("emps2 List : " + list1);
   }
}

Output
emps List  : [Ashok, Vinod, Dillesh, Latha]
emps1 List : [Ashok, Vinod, Dillesh, Latha, Janaki]
emps2 List : [Ashok, Vinod, Latha]
     If the object cloning was not provided, we will have to make database call to fetch the employee list every time. Then do the manipulations that would have been resource and time consuming.

Next Tutorial  Builder Design Pattern

Previous Tutorial  Abstract Factory Design Pattern Tutorial

No comments:

Post a Comment