Prototype Pattern

We’re going to create an abstract class Shape and concrete classes extending the Shapeclass. A class ShapeCache is defined as a next step which stores shape objects in aHashtable and returns their clone when requested.

PrototypPatternDemo, our demo class will use ShapeCache class to get a Shape object.

Prototype Pattern UML Diagram

Step 1

Create an abstract class implementing Clonable interface.

public abstract class Shape implements Cloneable {
   private String id;
   protected String type;
   abstract void draw();
   public String getType(){
      return type;
   public String getId() {
      return id;
   public void setId(String id) { = id;
   public Object clone() {
      Object clone = null;
      try {
         clone = super.clone();
      } catch (CloneNotSupportedException e) {
      return clone;

Step 2

Create concrete classes extending the above class.

public class Rectangle extends Shape {

   public Rectangle(){
     type = "Rectangle";

   public void draw() {
      System.out.println("Inside Rectangle::draw() method.");

public class Square extends Shape {

   public Square(){
     type = "Square";

   public void draw() {
      System.out.println("Inside Square::draw() method.");

public class Circle extends Shape {

   public Circle(){
     type = "Circle";

   public void draw() {
      System.out.println("Inside Circle::draw() method.");

Step 3

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

import java.util.Hashtable;

public class ShapeCache {
   private static Hashtable<String, Shape> shapeMap  = new Hashtable<String, Shape>();

   public static Shape getShape(String shapeId) {
      Shape cachedShape = shapeMap.get(shapeId);
      return (Shape) cachedShape.clone();

   // for each shape run database query and create shape
   // shapeMap.put(shapeKey, shape);
   // for example, we are adding three shapes
   public static void loadCache() {
      Circle circle = new Circle();

      Square square = new Square();

      Rectangle rectangle = new Rectangle();
      shapeMap.put(rectangle.getId(), rectangle);

Step 4

PrototypePatternDemo uses ShapeCache class to get clones of shapes stored in aHashtable.

public class PrototypePatternDemo {
   public static void main(String[] args) {

      Shape clonedShape = (Shape) ShapeCache.getShape("1");
      System.out.println("Shape : " + clonedShape.getType());		

      Shape clonedShape2 = (Shape) ShapeCache.getShape("2");
      System.out.println("Shape : " + clonedShape2.getType());		

      Shape clonedShape3 = (Shape) ShapeCache.getShape("3");
      System.out.println("Shape : " + clonedShape3.getType());		

Step 5

Verify the output.

Shape : Circle
Shape : Square
Shape : Rectangle