Using the Prototype Design Pattern In Java

Let's discuss today another creational design pattern named - Prototype Design Pattern.

Prototype Design Pattern

  • The Prototype Design Pattern is one of the twenty-three well-known GoF design patterns  which helps us copying an existing object rather than creating a new instance from scratch.
  • The Prototype pattern is used when we need to create a number of instances of a class and  each instance has almost same state or has very little difference.
  • The Prototype pattern is used when creation of actual object directly is costly as per resource and data it holds and also is a time taking.
  • The existing original object acts as a prototype and contains the state of the object. The new object is copy of the original object.
  • The Prototype pattern is used when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects.
  • We are free to change values in the newly copied object whenever we required. 
  • The Prototype pattern helps us to save costly resources and time, especially when the object creation is a heavy and time taking process.
  • In Java, One of the best available way to create object from existing objects are by using clone() method of Cloneable interface. Clone is the simplest approach to implement prototype pattern.
  • We can also implement Prototype interface by using Deep Copy method. 
    • Deep Copy - By Deep copy we create an object by copying all the fields of the original object. And also if the original object contains other objects as fields, we copy them as well. 
    • Shallow Copy - By Shallow copy we create an object by copying all the fields of the original object. But if the original object contains other objects as fields, we copy only the reference of those objects instead of copying complete object itself.
  • There are two ways of implementing the Prototype pattern
    • Basic Implementation
    • Prototype Registry Implementation

Basic ImplementationBasic Implementation