Prototype Pattern

The prototype pattern is a creational design pattern used in software development when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects. This pattern is used to:

  • avoid subclasses of an object creator in the client application, like the abstract factory pattern does.
  • 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.

Example:

Create class which should implement cloneable interface

public class Prototype implements Cloneable{

	public Prototype clone() throws CloneNotSupportedException {
		return (Prototype) super.clone();
	}

	public void printValueOfX(int x) {
		System.out.println("Value :" + x);
	}
}

Now create class and use prototype pattern to create object:

public class PrototypeImplementation {

	public static void main(String[] args) throws CloneNotSupportedException {

		Prototype prototype=new Prototype();

		for (int i = 0; i < 15; i++) {
			prototype=prototype.clone();
			prototype.printValueOfX(i);			
		}
	}

}

 

  • That’s it. Below is list of all design patterns link:

Creational Patterns:

Structural Patterns:

Behavioral Patterns:

 

Leave a Reply

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