DEV Community

Coder
Coder

Posted on • Originally published at itscoderslife.wordpress.com on

Prototype Design Pattern [Creational]

The prototype pattern should be used when the construction of new instances is inefficient. When the initialization of an object is expensive, you should consider using the prototype pattern.

  • The prototype pattern creates clone instances from a prototype object.
  • The clones are created by copying all the properties of the prototype instance.
  • The clones are independent objects.
  • Modifying the clone does not affect the prototype and vice versa.
  • Value types get ultimately copied upon assignment, whereas we need to implement the copying for reference types, that is for classes.
  • The prototype pattern creates new objects by copying a prototype object. Use this pattern if initializing an object is expensive.
  • Value types make implementing the prototype pattern very easy because they are automatically copied upon assignment.
  • The cloning of objects stands at the core of the prototype pattern.
  • To correctly clone objects, we must understand the difference between the shallow and the deep copy. I am going to provide code examples for that too.
  • Prototype: creation through delegation. Factory Method: creation through inheritance.

The prototype pattern creates new objects by copying a prototype object. Use this pattern if initializing an object is expensive.

Example: AddressBook – while creating a new contact of an employee in an organization the details like Basic Info, Address, Employment details, Notes & links will have empty prefills.

Link to understand Deep vs Shallow copy: https://wordpress.com/block-editor/post/itscoderslife.wordpress.com/930

Summary : The prototype pattern creates new instances by cloning a prototype object and copying all its properties, instead of constructing new objects. The copied instance is an independent object. Changing its properties doesn’t affect the cloned object. Use this pattern when creating new instances of a given type is inefficient.

Top comments (0)