Sunday, 24 April 2016

Prototype design pattern

Prototype design pattern

When creation of a an object is incredibly complex or costly, it makes sense to clone it for multiple independent use. E.g. if a employee object, on creation, needs to connect to the LDAP server to get the employee details. The connection to the LDAP server may be very costly and slow. Hence if the HR department & the Finance department need the employee’s detail, one object can be created for the employee and the second object can just be cloned (either shallow or deep) for the other department. For deep copy one may use either iterative copy of the nested objects or just do java serialization and deserialization.



/* Prototype */
public interface IPerson {
      public String getName();
      public IPerson clonePrototype();
}


public class Employee implements IPerson, Cloneable{
     
      private String name;
     
      public Employee() {
            //Get employee name from LDAP
            name = "Sumit";
      }

      @Override
      public String getName() {
            return name;
      }

      @Override
      public IPerson clonePrototype() {
            IPerson clone = null;
            try {
                  clone = (IPerson) this.clone();
            } catch (CloneNotSupportedException e) {
                  e.printStackTrace();
            }
            return clone;
      }

}

public class MainClass {
     
      public static void main(String[] args) {
            IPerson hrDepartmentObj = new Employee();
            IPerson financeDepartmentObj = hrDepartmentObj.clonePrototype();
            System.out.println("HR dept. :: "+hrDepartmentObj.getName());
            System.out.println("Finance dept. :: "+financeDepartmentObj.getName());
      }


}

Code link : https://github.com/sksumit1/DesignPatterns

No comments:

Post a Comment