Design Pattern

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

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:

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
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

3 years ago