Java Creational Design Patterns – Prototype Pattern

Prototype pattern comes under creational design pattern. As we know, in Java object creation process is time consuming and costly, so instead of creating object every time we can create copy of existing object. So using this design pattern we can create object in easiest way. In prototype pattern object cloning is used to create object copies, which is implemented using clone() method.

You can use this pattern if any of the below point applies-

  • the client application wants to avoid subclasses of an object creator
  • in your application you find using ‘new’ keyword to create object pretty expensive.

Prototype pattern doesn’t create new object it just create clone of it. It takes all the necessary data and stored data in memory and whenever new object is required, prototype pattern creates clone of the object and can be customized later.

<Here are ALL Java Design Patterns, explained in detail with examples>

Prototype Pattern by Example

Lets take a simple example which describes prototype design pattern. Clone() method is the easiest way to implement prototype pattern and how to copy existing object based is totally depending on your business model.

To implement prototype pattern, need to declare an abstract base class that specifies a pure virtual clone() method. Any class which derives itself from the abstract base class, it implements the clone() operation.

Here is our abstract class

We will define couple of concrete classes that implements above abstract class



Now we will define a class that will act as a store for us and keep the objects ready-


Running the Example



So using this way prototype design pattern utilities memory and time which was used in first object creation. This pattern eliminates the extra overhead of fetching and processing the data.

This is all about Prototype design pattern which provides easiest way to create object, because the client will not write code which invokes new operator for object creation, instead it calls clone() method to create object copies.

So we can say complex objects are created in a simple manner in a Prototype pattern. It also hides the complexity of object creation. And finally objects can be added and removed run time.

The source code is available in our Github repository.

Download Code

<Here are ALL Java Design Patterns, explained in detail with examples>

Add a Comment

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