Prototype Design Pattern in Java

Prototype pattern refers to creation of new objects through cloning of the existing objects. This type of design pattern comes under creational pattern as this pattern provides one of the best way to create an object. By creating a prototype, new objects are created by copying this prototype. This pattern is used when creation of object directly is costly.

For example, being the database operation costly, we create an object in first request and in subsequent requests we can cache the object, returns its clone as and when needed thus reducing the database calls.

Class Diagram

Prototype Pattern in Java

When to use

We want to add and remove objects at runtime.
We want to cache objects for better performance.
We can configure an application with classes dynamically.
We want to keep the number of classes in a system to be minimum.

Benefits

Speeds up instantiation of large, dynamically loaded classes.
Reduced sub-classing.

Disadvantages

Each subclass of Prototype must implement the Clone operation. Could be difficult with existing classes with internal objects with circular references or which does not support copying.

Implementation

Let’s create an abstract class Burger and concrete classes extending the Burger class. A class PrototypeCache is defined as a next step which stores Burger objects in a Hashtable and returns their clone when requested. The demo class, PrototypDemo, will use PrototypeCache class to get a Burger object.

Output

That’s all. Thank you for your reading.

Soumitra

Software Professional, I am passionate to work on web/enterprise application. For more information please go to about me. You can follow on Twitter. You can be a friend on Facebook or Google Plus or Linkedin

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.