Design Patterns - Prototype

design-patterns

// Design Patterns - The Prototype Pattern:

Prototype pattern refers to creating object while keeping performance 
in mind.  This involves cloning.

// 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) {
      this.id = id;
   }

   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.
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.");
   }
}

// Step 3: Create a class to get concrete object
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();
        circle.setId("1");
        shapeMap.put(circle.getId(),circle);

        Square square = new Square();
        square.setId("2");
        shapeMap.put(square.getId(),square);

        Rectangle rectangle = new Rectangle();
        rectangle.setId("3");
        shapeMap.put(rectangle.getId(), rectangle);
    }
}

// Step 4: Uses ShapeCache class to get clones of shapes
ShapeCache.loadCache();
Shape clonedShape = (Shape) ShapeCache.getShape("1");
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License