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.

     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

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

   public Object clone() throws CloneNotSupportedException {
      List<String> temp = new ArrayList<String>();
      for (String s : this.getEmpList()) {
      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();

      Employees emps1 = (Employees) emps.clone();
      Employees emps2 = (Employees) emps.clone();
      List<String> list = emps1.getEmpList();
      List<String> list1 = emps2.getEmpList();

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

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