Thursday, September 11, 2014

Prototype Design Pattern


Definition

Prototype Design Pattern is a creational pattern that uses cloning to create new object. Likewise in Lazy Initialization when the object under creation is large and resource intensive, we clone the object instead instantiation.

Intention
  1. Specifies object creation with prototypical instance.
  2. Creates new objects by copying this prototype.

Components

Client - Creates a new object by asking a prototype to clone itself.
Prototype - Declares an interface for cloning itself.
Concrete Prototype - Implements the operation for cloning itself.

Implementation

There are two types of flavors of this pattern.

  1. Use with Cloneable Interface which is a Marker Interface.
  2. Custom implementation of the pattern.
 Code(Use of Cloneable Interface)





Code(Custom Implementation)






 The above 2 examples depict that the client only has to create one object calling its constructor and passing argument as "John". Second time the same object is cloned calling clone() and doClone() methods respectively. Thus, the second time, the programe do not create a person object explicitly.

No comments: