Importance of Prototype Design Pattern

Issath Sesni
2 min readMay 23, 2021

--

What is prototype design pattern

Creating an object is expensive and go through several steps to create. This pattern is to copy an existing object rather than creating a new instance from scratch. We don’t use new keyword here. It allows us to hide the complexity of making new instances from the client. The copied object may change some properties only required. This approach saves resources and time. Using clone() method is one of the best way to create an object from existing objects. Object creation is expensive after a database operation. In that case, we can cache the object, returns its clone on next request and update the database when needed, it reduces database calls. We create an object at first time, and register it. After each call we clone that object.

Note : Prototype means prototype of actual object. Registry provides service to have all prototypes accessible using simple string parameters.

When to use the Prototype Design Pattern

  • When a system should be independent of how its products are created, composed, and represented.
  • When the classes are instantiated at runtime.

Advantages

  • Adding and removing products at run-time.
  • Specifying new objects by varying values.
  • Specifying new objects by varying structure.
  • Reduced the need of sub classing.

Disadvantages

  • Very few objects and/or does not have an underlying emphasis on the extension of prototype chains makes overkill the project.
  • Hiding the complexity of concrete classes from the client.
  • Each subclass of Prototype must implement the clone() operation which may be difficult, when the classes under consideration already exist. Also implementing clone() can be difficult when their internals include objects that don’t support copying or have circular references.

Real world examples :- Shopping card, Rent a car system, etc.

There are 2 types of copying an object.

  1. Shallow copy :- Cloning from level 1 architecture. It makes a separate new object, i.e instead of copying the child elements to the new object, it simply copies the references to their memory addresses. It is quite difficult, because if you make any change in the original object, it will not be updated in the copied object.
  2. Deep copy :- It creates a new object and recursively adds the copies of nested objects present in the original elements.

UML diagram for a real world prototype pattern example.

--

--