Prototype Design Pattern

Chamal Weerasinghe
2 min readMay 22, 2021

--

Photo by Sigmund on Unsplash

What is Prototype Design Pattern

Other than the simple applications when it comes to the enterprise application there are many objects that have to be created. Objects are expensive memory resources to the heap. And creating hundred of thousands of objects can cause performance issues of an application.

To avoid this performance bottleneck prototype design pattern provides the capability of cloning the objects rather than creating them from the scratch. In detail, the objects are created and stored in the registry clone the objects using the registry when it needs.

In this cloning process, there are two ways of cloning object data.

  1. Shallow Copy - Where all the values of the object are copied to a new object. and it always copies the original values from primitive variables and from the non-primitive (objects) it copies the reference of the object, because of this if the original object’s attributes are changed then it will affect the cloned objects.
  2. Deep Copy - Deep copy makes separately allocated objects, here the original objects and the copied objects are independent of each other

Implementing Prototype Design Patterns

The following example is about airline trips and how to use a prototype design pattern to clone objects for a feature like searching flights. First, we create the necessary model classes.

First, we create the base class “Ticket” and in order to be able to clone we implement the “Clonable” object. this is a shallow copy.

Now we create subclasses for Economy tickets and Business class tickets.

Now for each search rather than creating a separate object, we create objects from and add them into the registry for clone and get when needed.

Get the clone of an object when needed.

--

--

No responses yet