Prototype Pattern

Ayesha Perera
3 min readJul 20, 2022

--

There are some situations, creating an object is very expensive. So this design pattern encourages you to clone the object. That means avoiding creation.

As for cloning the objects, Java uses the Cloneable interface.

When you clone it, you must pay attention to whether you need a shallow copy or a deep copy.

Shallow Copy

  • A shallow copy means, you just copy the first level object(references) to the new object.
  • This is quite a dangerous way because you clone an object and when you do any changes to the second object(cloned object) reference types, it will affect the first object also.

Deep Copy

  • But deep copy means, you go inside and copy(clone) each and every object and value to the new object.

Let’s go for an example.

  • Vehicle class

Create the Vehicle class with two private variables and the setter methods. To use cloning, you should implement the Cloneable interface and override the clone() method.

  • Car and Bus classes

Create both classes and extends with the Vehicle class.

  • Registry class

Create new instances of Bus and Car, inside the initialize method and put them into the vehicles hashmap. Then call initialize method, inside the Registry constructor.

There is a method called getVehicle(). When it is called by the main class, it gets the vehicle type and clones that particular object and return it.

  • VehicleType enum
  • Application class

Create a new Registry object inside the main method. So it reads the Registry constructor and executes the initialize method. After that call getVehicle() method with Vehicle type. So it gets the cloned object and prints it.

In line 11, it does some changes to the car object variable types. But it didn't affect the original object.

you can see in line 14, that it creates a Car object again, but it didn’t affect by line 11.

It gives the output as above.

  • Prototype Pattern is not much used in Programs because it involves registries. So we can see these types of things mostly in frameworks.

Thank you and Happy Learning!

--

--