Prototype Design Pattern – Creational Patterns

Prototype Design Pattern is used to create the objects by using clone method of object. In the enterprise application, when object creation is costly in terms of creating and initializing the initial properties of objects. If such type of object is already in your hand, then you go for prototype pattern. The prototype pattern comes under the creational design pattern family of GOF patterns in software development.

Prototype Design Pattern

According to the Gang of Four:

Specify the kind of objects to create using a prototypical instance, and create new objects by copying this prototype.

This pattern involves implementing a prototype interface which tells to create a clone of the current object. This pattern is used when creation of object directly is costly. For example, an object is to be created after a costly database operation. We can cache the object, returns its clone on next request and update the database as and when needed thus reducing database calls.

Spring 5 Design Pattern Book

You could purchase my Spring 5 book that is with title name “Spring 5 Design Patterns“. This book is available on the Amazon and Packt publisher website. Learn various design patterns and best practices in Spring 5 and use them to solve common design problems. You could use author discount to purchase this book by using code- “AUTHDIS40“.
Spring-5-Design-Pattern

UML class diagram of the Prototype Pattern

Let’s see the following class diagram for the Prototype design pattern and it illustrates about the component classes:

Prototype Design Pattern

The classes and objects participating in this pattern are:

Prototype (Account)

  • It is an interface using in to create the clone of it.

ConcretePrototype (SavingAccount, CurrentAccount)

  • It is a concrete class of Prototype interface to implement an operation for cloning itself.

Client (PrototypePatternMain)

  • It is a caller class to create a new object of a prototype interface by calling clone method of it.

Applicability

There are following applicability where we have to Use the Prototype Pattern:

  • The classes to instantiate are specified at run time, for example, by dynamic loading.
  • To avoid building a class hierarchy of factories that parallels the class hierarchy of products.
  • When instances of a class can have one of only a few different combinations of state.
  • When the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects.
  • It avoid subclasses of an object creator in the client application, like the abstract factory pattern does.
  • This pattern is used to avoid the inherent cost of creating a new object in the standard way (e.g., using the ‘new’ keyword) when it is prohibitively expensive for a given application.

Pros of the Prototype Design Pattern

There are following pros of using the Prototype pattern:

  • Reduce the time complexity to creating the time consuming objects by using the prototype pattern.
  • Prototype pattern reduces the sub-classing.
  • It adds and removes objects at run time.
  • We can use this pattern to configure the application with classes dynamically.

Cons of the Prototype Design Pattern

There are following cons of using the Prototype pattern:

  • Constructor separate from prototype definition

Sample Implementation of Prototype Design Pattern

I am going to create an abstract class Account and concrete classes extending the Account class. A class AccountCache is defined as a next step which stores account objects in a HashMap and returns their clone when requested.

Step 1 : Create an abstract class implementing Clonable interface.

Account.java

package com.doj.patterns.creational.prototype;

/**
 * @author Dinesh.Rajput
 *
 */
public abstract class Account implements Cloneable{
	abstract public void accountType();
	public Object clone() {
		Object clone = null;
		try {
			clone = super.clone();
		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
		}
		return clone;
	}
}

Step 2: Create concrete classes extending the above class.

CurrentAccount.java

package com.doj.patterns.creational.prototype;

/**
 * @author Dinesh.Rajput
 *
 */
public class CurrentAccount extends Account {
	@Override
	public void accountType() {
		System.out.println("CURRENT ACCOUNT");
	}
}

SavingAccount.java

package com.doj.patterns.creational.prototype;

/**
 * @author Dinesh.Rajput
 *
 */
public class SavingAccount extends Account{
	@Override
	public void accountType() {
		System.out.println("SAVING ACCOUNT");
	}
}

Step 3: Create a class to get concrete classes from database and store them in a Hashtable.

AccountCache.java

package com.doj.patterns.creational.prototype;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Dinesh.Rajput
 *
 */
public class AccountCache {
	public static Map<String, Account> accountCacheMap = new HashMap<>();
	
	static{
		Account currentAccount = new CurrentAccount();
		Account savingAccount = new SavingAccount();
		accountCacheMap.put("SAVING", savingAccount);
		accountCacheMap.put("CURRENT", currentAccount);
	}
}

Step 4: Let’s create a demo class PrototypePatternMain uses AccountCache class to get clones of accounts stored in a Hashtable.

PrototypePatternMain.java

package com.doj.patterns.creational.prototype;

/**
 * @author Dinesh.Rajput
 *
 */
public class PrototypePatternMain {

	public static void main(String[] args) {
		Account currentAccount = (Account) AccountCache.accountCacheMap.get("CURRENT").clone();
		currentAccount.accountType();
		Account savingAccount = (Account) AccountCache.accountCacheMap.get("SAVING") .clone();
		savingAccount.accountType();
	}
}

Step 5: Let’s run the above class and verify the output.

CURRENT ACCOUNT
SAVING ACCOUNT

Previous
Next