vendredi 4 novembre 2016

what is the benefit of prototype pattern in this case

I saw some code defines the prototype pattern in this way :

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;
   }
}

Two concrete classes extending the above class :

public class Rectangle extends Shape {

   public Rectangle(){
     type = "Rectangle";
   }

   @Override
   public void draw() {
      System.out.println("Inside Rectangle::draw() method.");
   }
}
public class Square extends Shape {

   public Square(){
     type = "Square";
   }

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

Create a class to get concrete classes from database and store them in a 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();
   }


   public static void loadCache() {

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

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

My question is in the getShape method what is the difference and benefit between these two implementations :

Implementation 1 :

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

And : Implementation 2 :

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

I tried the two implementations and they work well just I want to know the benefit if I use the first Implementation

Aucun commentaire:

Enregistrer un commentaire