Prototype Design Pattern

Download the working example demo code in java from my GIT repository –

Code Example
The Prototype pattern specifies the kind of objects to create using a prototypical instance. Cell is the abstract class with different subclasses like singleCell Organism, amoeba, bacteria etc. For each sub class a breeder object is created before hand and registered in class. Now whenever client program wants to breed or culture a particular organism say amobea they will fetch it from cache and invoke split/clone method which will provide replicated organism with same state property. Download the example code and have fun.
 Example of Prototype

When creating an object is time consuming and a costly affair and you already have a most similar object instance in hand, then you go for prototype pattern. Instead of going through a time consuming process to create a complex object, just copy the existing similar object and modify it according to your needs. Clone the existing instance in hand and then make the required update to the cloned instance so that you will get the object you need. Other way is, tweak the cloning method itself to suit your new object creation need.

Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.
  • Co-opt one instance of a class for use as a breeder of all future instances.
  • The new operator considered harmful.
Application “hard wires” the class of object to create in each “new” expression.
Declare an abstract base class that specifies a pure virtual “clone” method, and, maintains a dictionary of all “cloneable” concrete derived classes. Any class that needs a “polymorphic constructor” capability: derives itself from the abstract base class, registers its prototypical instance, and implements the clone() operation.

The client then, instead of writing code that invokes the “new” operator on a hard-wired class name, calls a “clone” operation on the abstract base class, supplying a string or enumerated data type that designates the particular concrete derived class desired.

Prototype Design Pattern

Check list
Add a clone() method to the existing “product” hierarchy.
  1. Design a “registry” that maintains a cache of prototypical objects. The registry could be encapsulated in a new Factory class, or in the base class of the “product” hierarchy.
  2. Design a factory method that: may (or may not) accept arguments, finds the correct prototype object, calls clone() on that object, and returns the result.
  3. The client replaces all references to the new operator with calls to the factory method.
Rules of thumb
  • Prototype co-opts one instance of a class for use as a breeder of all future instances.
  • Prototypes are useful when object initialization is expensive, and you anticipate few variations on the initialization parameters. In this context, Prototype can avoid expensive “creation from scratch”, and support cheap cloning of a pre-initialized prototype.
  • Factory Method: creation through inheritance. Protoype: creation through delegation.
  • Often, designs start out using Factory Method (less complicated, more customizable, subclasses proliferate) and evolve toward Abstract Factory, Protoype, or Builder (more flexible, more complex) as the designer discovers where more flexibility is needed.
  • Prototype doesn’t require subclassing, but it does require an “initialize” operation. Factory Method requires subclassing, but doesn’t require Initialize.
  • Designs that make heavy use of the Composite and Decorator patterns often can benefit from Prototype as well.

Java Cloning concept explained in detail

Clone (κλών) is a Greek word meaning “branch”, referring to the process whereby a new plant can be created from a twig. In biology it is about copying the DNAs. In Programming action of copying the attributes of one object into another of same data type is called object copy or Cloning. The main object from which we clone could be thought of as “Breeder” which might have several shallow or deep copies/replicas. Cloning is used where we need to save a lot of time and trouble of creating object by new keyword and then initializing/processing them to attain similar object state. With cloning new object with similar object states comes out of the box by virtue of clone() method defined in Object class of javaSmile 

I have an object called as Employee which has below fields :

Now if we need to construct several objects of similar type either we can use new operator and initialize each object or we can just use the clone method (provided by Object class – mother of all objects). By virtue of cloning, newly created object from clone will have all the values copied –  the object reference of Department, salary account and even id – oops Winking smile this copy is called as shallow copy. Actually department is ok, but id and provident funds account should be entirely new/different for each employee. So the to modify or create a new object which does not blindly copy object reference and values, rather has their own object graph we use Deep copy Smile . Visit this github link to have a look at the code.

How will you achieve cloning in java?

In Java everything is achieved through class, object and interface .By default no Java class support cloning but Java provide one interface called Cloneable, which is a marker interface and by implementing this interface we can make duplicate copy of our object by calling clone() method of java.lang.Object class. This Method is protected inside the object class and Cloneable interface is a marker interface and this method also throw  CloneNotSupportedExceptionif we have not implement this interface and try to call clone() method of Object class. By default any clone() method gives shallow copy of the object i.e. if we invoke super. clone() then it’s a shallow copy but if we want to deep copy we have to override theclone() method and make it public and give own definition of making copy of object. Now we let’s see what is shallow and deep copy of object in Java programming language.

Shallow Copy

Whenever we use default implementation of clone method we get shallow copy of object means it create new instance and copy all the field of object to that new instance and return it as object type we need to explicitly cast it back to our original object. This is shallow copy of the object. clone() method of the object class support shallow copy of the object. If the object contains primitive as well as non primitive or reference type variable In shallow copy, the cloned object also refers to the same object to which the original object refers as only the object references gets copied and not the referred objects themselves. That’s why the name shallow copy or shallow cloning in Java. If only primitive type fields or Immutable objects are there then there is no difference between shallow and deep copy in Java.

In shallow copy, a new object is created which contains the exact copy of the values in the original object. Shallow copy follows the bit-wise copy approach. In shallow copy if the field is a memory address, then the address is copied. Thus if the address is changed by one object, the change gets reflected everywhere.


Figure 1: The flow chart describes shallow copy

In this figure, the object – mainObj1 has fields field1 of a primitive type say int, and an object of type String When we do a shallow copy of mainObj1, mainObj2 is created with field2 of type int which contains the copied value of field1 but the String object in mainObj2 – still points to objStr itself. Since field1 is a primitive data type, the value of it is copied into field2. But since objStr is an object, mainObj2 is pointing to the same address of objStr. So any changes made to objStr via mainObj1 get reflected in mainObj2.

Deep Copy

Whenever we need a non shared object graph for newly cloned object we do deep cloning. This can be done in multiple ways while doing overriding clone() we can add our logic for new assignments to the object reference or we have to ensure that all the member class also implement Cloneable interface and override the clone() method of the object class.

In deep copy, not only all the fields of an object are copied, all the dynamically allocated memory address which are pointed by that object are also copied.


Figure 2: The diagram describes deep copy process

In this figure, the object mainObj1 has fields field1 a primitive data type say int, and an object of type String When we do a deep copy of mainObj1, mainObj2 is created with field2 containing the copied value of field1 and objStr2 is created which contains the copied value of objStr1 So any changes made to objStr1 in mainObj1 will not reflect in mainObj2.

Lazy Copy

A lazy copy can be defined as a combination of both shallow copy and deep copy. The mechanism follows a simple approach – at the initial state, shallow copy approach is used. A counter is also used to keep a track on how many objects share the data. When the program wants to modify the original object, it checks whether the object is shared or not. If the object is shared, then the deep copy mechanism is initiated.


Difference between Shallow and Deep Copy in Java

I think now we know what is deep and shallow copy of object in Java, let see some difference between them so that we can get some more clarity on them.

  • When we call Object.clone(), this method performs a shallow copy of object, by copying data field by field, and if we override this method and by convention first call super.clone(), and then modify some fields to “deep” copy, then we get deep copy of object. This modification is done to ensure that original and cloned object are independent to each other.
  • In shallow copy main or parent object is copied, but they share same fields or children if fields are modified in one parent object other parent fields have automatic same changes occur,but in deep copy this is not the case.
  • If our parent object contains only primitive value then shallow copy is good for making clone of any object because in new object value is copied but if parent object contains any other object then only reference value is copied in new parent object and both will point to same object so in that case according to our need we can go for deep copy.
  • Deep copy is expensive as compare to shallow copy in terms of object creation, because it involves recursive copying of data from other mutable objects, which is part of original object.