Prototype Design Pattern

Anuradha Gunasinghe
2 min readMay 22, 2021

--

What is the Prototype design pattern?

Prototype 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.

Prototype 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. There are two types of cloning: deep copy and shallow copy.

Shallow Copy

The shallow copy of an object will have exact copy of all the fields of original object. If original object has any references to other objects as fields, then only references of those objects are copied into clone object, copy of those objects are not created. That means any changes made to those objects through clone object will be reflected in original object or vice-versa. Shallow copy is not 100% disjoint from original object. Shallow copy is not 100% independent of original object.

  • Cloned Object and original object are not 100% disjoint.
  • Any changes made to cloned object will be reflected in original object.
  • Default version of clone method creates the shallow copy of an object.
  • Shallow copy is preferred if an object has only primitive fields.
  • Shallow copy is fast and also less expensive.

Deep Copy

Deep copy of an object will have exact copy of all the fields of original object just like shallow copy. But in additional, if original object has any references to other objects as fields, then copy of those objects are also created by calling clone() method on them. That means clone object and original object will be 100% disjoint. They will be 100% independent of each other. Any changes made to clone object will not be reflected in original object.

  • Cloned Object and original object are 100% disjoint.
  • Any changes made to cloned object will not be reflected in original object.
  • To create the deep copy of an object, you have to override clone method.
  • Deep copy is preferred if an object has references to other objects as fields.
  • Deep copy is slow and very expensive.

--

--

Anuradha Gunasinghe

Software Engineer @ WTS, Bachelor of Engineering (BEng) Honours in Software Engineering Graduated from University of Westminster