Prototype pattern

Tharaka Dissanayake
2 min readJul 2, 2022

--

The Prototype pattern is a creational design pattern. This pattern is used to copy an existing object.

Example:

Think, there are products to sell. There is a “Product” interface, and several products will implement it.

So, we need to create product objects when we print product items on the bill. For creating a product object (Book) “Bill” class must be known all the products. We should edit the “Bill” class when adding a new product. It will violate the open-close principle. It means Classes should close for modification but open for extension. Another problem is the “Bill” class must know about all the products. (Tight coupling).

Therefore, this implanting way should differ as follows.

First, we must separate the cloning method to the Product interface from the “Bill” class. Each product should have a clone method because each class must encapsulate cloning techniques for each item. Also, there must be a clone method in the Product interface because all products can be cloned. Now, the “Product” interface behaves as a prototype for all the products.

Product interface
The “Book” class that was implemented by the Product interface

The “clone” method gives the new object.

The “Bill” class.

The “Bill” class does not want to know what is the cloned object.

--

--

Tharaka Dissanayake
Tharaka Dissanayake

No responses yet