Prototype Design Pattern Implementation

The following two tabs change content below.
Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

Latest posts by Prasad Kharkar (see all)

Let us learn yet another creational design pattern in this article. Prototype design pattern implementation allows us to solve the problem of having multiple copies of objects those are expensive and resource intensive to create.

Prototype Design Pattern Implementation:

Gang of Four book defines prototype design pattern as below

Specifies kind of objects to created using prototypical instance and create new object by copying this object

Generic class diagram is as below


Prototype pattern class diagram

  • Client: references to Prototype and instantiates ConcretePrototype.
  • Prototype : An interface which declares methods for cloning the object.
  • ConcretePrototype: A concrete class which implements Prototype interface

Prototype design pattern implementation helps us get multiple copies of one object without having to worry about expenses of creating a new object. In java, prototype design pattern implementation can be achieved by using Cloneable interface. Although clone method is defined in Object class, we have to implement Cloneable for some reason which we will not discuss here.

Prototype Design Pattern Implementation

This program outputs,

Creating a new object now
Time required = 2000
Object creation done
Creating clone now
Time required = 0
Clone created

  • We have created Bike constructor such that it takes 2000 milliseconds to simulate expensive object creation which takes lot of time. We are printing out time spent in constructing Bike object using constructor.
  • Then Client calls bike.clone() method which quickly creates another object without taking much time.
  • This helps us create multiple object clones where creation of object is expensive and resource intensive.

I hope prototype design pattern implementation helped.

Happy learning 🙂


Share Button

Leave a Reply

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