Design Pattern (Part 03)— Prototype Design Pattern!

Advantage of Prototype Pattern

1.The clients can get new objects without knowing which type of object they will be
2. It hides the complexities of creating objects.
3. Add or remove objects at runtime.
4. Save total operating cost by minimizing costly external API calls.

UML for Prototype Pattern

Prototype Design Pattern Implementation

  1. Create a Product class that implements the cloneable interface. List all the parameters and create a setter getter for them. Create appropriate constructors.
  2. If parameters contain all immutable fields, there is no need to override the clone() method.
  3. If any parameter is mutable, We need to override the clone() method and write appropriate deep cloning logic.
  4. The clone method will return a new object of the Product class with all field values as per the original product object.

Real-world Example

In this scenario, imagine we have different kinds of Flights in the airport as Malaysian Airways, Emirates Airways, Qatar Airways. All these three flight types are subclasses of the class Flight that implements the base functionalities and base attributes of different flights, such as numberOfSeats, type, businessclass, FuelType, engineCapacity. Registry class is used for when a user asks for flight type, they can pass that flight type they want and get a clone of the pre-created instance of Malaysian Airways, Emirates Airways, Qatar Airways classes. After obtaining cloned instance, if we like we can set different values to each class attributes.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store