设计模式之原型模式

126 阅读1分钟

原型模式用于创建重复的对象,同时又能保证性能,创建一个对象的代价较大时可以采用这种模式。

意图

通过原型实例来指定创建对象的种类,并通过拷贝这些对象来创建对象。

实现

创建实现cloneable接口的抽象类

public abstract class Shape implements Cloneable {
    private int ID;
    protected String type;

    abstract void Draw();

    public int getID() {
        return ID;
    }

    public void setID(int ID) {
        this.ID = ID;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public Object clone() {
        Object clone = null;
        try {
            clone =super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return clone;
    }
}

扩展抽象类

public class Circle extends Shape {
    @Override
    void Draw() {
        System.out.println("Shape");
    }

    public Circle() {
        this.type = "circle";
    }
}
public class Rectangle extends Shape {
    @Override
    void Draw() {
        System.out.println("Rectangle");
    }

    public Rectangle() {
        this.type = "Rectangle";
    }
}
public class Triangle extends Shape {
    @Override
    void Draw() {
        System.out.println("Triangle");
    }

    public Triangle() {
        this.type = "Triangle";
    }
}

创建一个类,获取对象然后存入hashtable

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

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

    public static void loadShapeCache() {
        Circle circle = new Circle();
        circle.setID(1);
        shapeMap.put(String.valueOf(circle.getID()), circle);

        Triangle triangle = new Triangle();
        triangle.setID(2);
        shapeMap.put(String.valueOf(triangle.getID()), triangle);

        Rectangle rectangle = new Rectangle();
        rectangle.setID(3);
        shapeMap.put(String.valueOf(rectangle.getID()), rectangle);
    }
}

通过创建的类来获取对象的克隆

public class ProtoTypePatternDemo {
    public static void main(String[] args) {
        ShapeCache.loadShapeCache();

        Shape cloneShape = ShapeCache.getShape("1");
        System.out.println(cloneShape.getType());

        Shape cloneShape1 = ShapeCache.getShape("2");
        System.out.println(cloneShape1.getType());

        Shape cloneShape2 = ShapeCache.getShape("3");
        System.out.println(cloneShape2.getType());
    }
}