Sitemap

Prototype pattern

2 min readJul 2, 2022

--

Press enter or click to view image in full size

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).

Get Tharaka Dissanayake’s stories in your inbox

Join Medium for free to get updates from this writer.

Therefore, this implanting way should differ as follows.

Press enter or click to view image in full size

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.

Press enter or click to view image in full size
Product interface
Press enter or click to view image in full size
The “Book” class that was implemented by the Product interface

The “clone” method gives the new object.

Press enter or click to view image in full size
The “Bill” class.

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

--

--