Prototype design pattern in java

A prototype is a template of any object before the actual object is constructed. In java also, it holds the same meaning. Prototype design pattern is used in scenarios where application needs to create a number of instances of a class, which has almost same state or differs very little.

Ads by Google

Download source code

In this design pattern, an instance of actual object (i.e. prototype) is created on starting, and thereafter whenever a new instance is required, this prototype is cloned to have another instance. The main advantage of this pattern is to have minimal instance creation process which is much costly than cloning process.

Sections in this post:
Design participants
Problem statement
Implementation

Important: Please ensure that you want to deep clone or shallow clone your prototype because both will have different behavior on runtime. If deep copy is needed, you can use a good technique given here using in memory serialization.

Design participants

  • Prototype : This is the prototype of actual object as discussed above.
  • Prototype registry : This is used as registry service to have all prototypes accessible using simple string parameters.
  • Client : Client will be responsible for using registry service to access prototype instances.

Problem statement

Lets understand this pattern using an example. I am creating an entertainment application that will require instances of Movie, Album and Show classes very frequently. I do not want to create their instances everytime as it is costly. So, I will create their prototype instances, and everytime when i will need a new instance, I will just clone the prototype.

Implementation of prototype pattern

Lets start by creating class diagram.

prototype-pattern-class-diagram

Above class diagram explains the necessary classes and their relationship.

Ads by Google

Only one interface, “PrototypeCapable” is new addition in solution. The reason to use this interface is broken behavior of Cloneable interface. This interface helps in achieving following goals:

  • Ability to clone prototypes without knowing their actual types
  • Provides a type reference to be used in registry

Their workflow will look like this:

Prototype pattren sequence diagram

Lets hit the keyboard and compose these classes.

PrototypeCapable.java

package com.howtodoinjava.prototypeDemo.contract;

public interface PrototypeCapable extends Cloneable
{
	public PrototypeCapable clone() throws CloneNotSupportedException;
}

Movie.java, Album.java and Show.java

package com.howtodoinjava.prototypeDemo.model;

import com.howtodoinjava.prototypeDemo.contract.PrototypeCapable;

public class Movie implements PrototypeCapable
{
	private String name = null;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	@Override
	public Movie clone() throws CloneNotSupportedException {
		System.out.println("Cloning Movie object..");
		return (Movie) super.clone();
	}
	@Override
	public String toString() {
		return "Movie";
	}
}

public class Album implements PrototypeCapable
{
	private String name = null;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	@Override
	public Album clone() throws CloneNotSupportedException {
		System.out.println("Cloning Album object..");
		return (Album) super.clone();
	}
	@Override
	public String toString() {
		return "Album";
	}
}

public class Show implements PrototypeCapable
{
	private String name = null;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	@Override
	public Show clone() throws CloneNotSupportedException {
		System.out.println("Cloning Show object..");
		return (Show) super.clone();
	}
	@Override
	public String toString() {
		return "Show";
	}
}

PrototypeFactory.java

package com.howtodoinjava.prototypeDemo.factory;

import com.howtodoinjava.prototypeDemo.contract.PrototypeCapable;
import com.howtodoinjava.prototypeDemo.model.Album;
import com.howtodoinjava.prototypeDemo.model.Movie;
import com.howtodoinjava.prototypeDemo.model.Show;

public class PrototypeFactory
{
	public static class ModelType
	{
		public static final String MOVIE = "movie";
		public static final String ALBUM = "album";
		public static final String SHOW = "show";
	}
	private static java.util.Map<String , PrototypeCapable> prototypes = new java.util.HashMap<String , PrototypeCapable>();

	static
	{
		prototypes.put(ModelType.MOVIE, new Movie());
		prototypes.put(ModelType.ALBUM, new Album());
		prototypes.put(ModelType.SHOW, new Show());
	}

	public static PrototypeCapable getInstance(final String s) throws CloneNotSupportedException {
		return ((PrototypeCapable) prototypes.get(s)).clone();
	}
}

TestPrototypePattern

package com.howtodoinjava.prototypeDemo.client;

import com.howtodoinjava.prototypeDemo.factory.PrototypeFactory;
import com.howtodoinjava.prototypeDemo.factory.PrototypeFactory.ModelType;

public class TestPrototypePattern
{
	public static void main(String[] args)
	{
		try
		{
			String moviePrototype  = PrototypeFactory.getInstance(ModelType.MOVIE).toString();
			System.out.println(moviePrototype);

			String albumPrototype  = PrototypeFactory.getInstance(ModelType.ALBUM).toString();
			System.out.println(albumPrototype);

			String showPrototype  = PrototypeFactory.getInstance(ModelType.SHOW).toString();
			System.out.println(showPrototype);

		}
		catch (CloneNotSupportedException e)
		{
			e.printStackTrace();
		}
	}
}

When you run the client code, following is the output.

Cloning Movie object..
Movie
Cloning Album object..
Album
Cloning Show object..
Show

I hope, you liked this post. If any question, drop a comment.

Download source code

Happy Learning !!

9 thoughts on “Prototype design pattern in java”

  1. Very good article,easy to understand the design patterns with real examples and also with perfect class diagram.
    Really useful

  2. I didn’t see much of value of introducing PrototypeCapable interface to enable clone() method, which is build-in in Object. It is not the contract obligation broken on Cloneable in java, it is the implementation was build-in for a purpose to make sure the Clone mechanism is working even across inheritance hierarchy, otherwise, the type inheritance will be mismatch. That means, there is no free way to correctly implement “clone” behavior defined in PrototypeCapable interface other than call “super.clone()” which binding to Object.clone build-in mechanism. What’s the point?

    1. In java, to make an object cloning supported, it takes two steps: 1) Implement Cloneable 2) Override clone()

      Lets say, a new developer joined a team which knows only basics in java. He is assigned a task in which he has to add one more object in prototype registry(factory) i.e. “Ticket”.

      By which design, you can force that developer to perform above both steps??

      It is only possible when you tie both steps together otherwise behavior will be surprising.

  3. Dear Lokesh
    ModelType is static subclass of PropertyFactory class ,so Following correction is required in running class TestPropertytypePattern

    String moviePrototype = PrototypeFactory.getInstance(PrototypeFactory.ModelType.MOVIE).toString();

    rest is fine ,I have tested it

Note:- In comment box, please put your code inside [java] ... [/java] OR [xml] ... [/xml] tags otherwise it may not appear as intended.

Want to ask any question? Or suggest anything?