1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| import java.util.Hashtable;
class Square extends Shape {
public Square(){ type = "Square"; }
@Override public void draw() { System.out.println("draw square"); } }
class Circle extends Shape {
public Circle(){ type = "Circle"; }
@Override public void draw() { System.out.println("draw circle"); } }
class ShapeCache {
private static final Hashtable<String, Shape> shapeMap = new Hashtable<>();
public static Shape getShape(String shapeId) { Shape cachedShape = shapeMap.get(shapeId); return (Shape) cachedShape.clone(); }
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); } }
public class PrototypePatternDemo { public static void main(String[] args) { ShapeCache.loadCache(); Shape clonedShape = (Shape) ShapeCache.getShape("1"); System.out.println("Shape : " + clonedShape.getType()); Shape clonedShape2 = (Shape) ShapeCache.getShape("2"); System.out.println("Shape : " + clonedShape2.getType()); } }
|