Introduction
Prototype design pattern is one of a creational design pattern. This pattern can be used when user wants to have an object but without instanciating it. That means using java clone feature. The advantage of this pattern is as you might know creating an object using new operator is very costly. But here we use clone method to create new objects. But you know if we want to create an object using clone method there should be existing object to make clone objects. So first object creation should be done by using the java new operator.
Example
Suppose you want to draw some shapes. For example you want to draw shapes like Square, Triangle. But these drawing not only once. many times you want to draw Square and Triangle. In other words, you have to make instances of Square and Triangle classes. But you want to avoid that instance creation but make instances by cloning. So it is the prototype design pattern.
Following example code has Shape abstract class and Square and Triangle concrete classes. As you can see Shape class implement with Cloneable interface so that it can implement of cloning logic.
Following example code has Shape abstract class and Square and Triangle concrete classes. As you can see Shape class implement with Cloneable interface so that it can implement of cloning logic.
Shape.java
package com.blog.patterns.prototype; /** * @author uditha */ public abstract class Shape implements Cloneable { public abstract void draw(); @Override public Object clone() { Object clone = null; try { clone = super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return clone; } }
Square.java
package com.blog.patterns.prototype; /** * @author uditha */ public class Square extends Shape { @Override public void draw() { System.out.println("Square"); } }
Triangle.java
package com.blog.patterns.prototype; /** * @author uditha */ public class Triangle extends Shape { @Override public void draw() { System.out.println("Triangle"); } }
Main.java
package com.blog.patterns.prototype; /** * @author uditha */ public class Main { public static void main(String[] args) { Shape squareA = new Square(); squareA.draw(); Shape squareB = (Square) squareA.clone(); squareB.draw(); Shape triangleA = new Triangle(); triangleA.draw(); Shape triangleB = (Triangle) triangleA.clone(); triangleB.draw(); } }