Introduction to Prototype Design Pattern
The prototype design pattern is different from the Singleton and Factory method design patterns which we discussed previously.
The prototype design pattern is all about avoiding creation. Did you know that creating a new object is very expensive? Therefore, what prototype design pattern does is, encourages to clone of an existing object
Consider the following scenario: we’re designing an application for air traffic control. You might want to display 100 or more than 1000 aeroplanes in such a system. As a result, you’ll need to create tens of thousands of objects in the system (Which is system resource-wise, a bit expensive).
So, what if you could only make one object and clone it?
If creating a new object is expensive and if there are too many things to do when creating an object, this is the design pattern you are looking for.
Since this is a way of cloning, we use the Java Cloneable interface. Clone()
always returns an object type. Therefore, always make sure to Cast the returning object to the type needed. When you are cloning an object, there are 02 questions that you need to ask yourself.
In your architecture, do you need a shallow copy? or a deep copy?
When creating a shallow copy, you only get first-level objects and references to the new object. But when creating a deep copy, you clone each and every object and the values to the new object. So whether you need a shallow copy or a deep copy depends on your requirement.
Now let’s try an implementation of the prototype design pattern.
Assume “Amazen” is an e-commerce system owned by “John Bee,” a billionaire. They want to deploy drones to pick up selling items from warehouses in 2022 and deliver them to millions of customers.
There are several types of drones. For normal deliveries they use “Fantom-Normal”, For fast deliveries “SensFly-Fast” and for deliveries more than 10KG weight a special drone called “Herculean-Power” is used. According to their requirements, each drone should be indicated on a monitor.
But the problem is they have thousands of drones and to indicate each one of them they have to create a new object from drone class. Well, creating few drone objects might be okay. But thousands of them could be troublesome with the memory. So that’s when they decide to use the prototype design pattern.
I have added the implementation of the above scenario in my GitHub repository (inside Design patterns/Prototype design pattern directory). If you are looking for an implementation I like to suggest you have a look at that coding example.