设计模式-原型模式

        原型模式是一种创建型设计模式,它用于创建重复的对象,同时又能保证性能。这种类型的设计模式是基于一个原型实例,通过复制(克隆)自身来创建新的对象。

        以下是一个简单的 Java 版本的原型模式的示例:

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

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

public class ShapeCache {
    private static Hashtable shapeMap  = new Hashtable();

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

    public static void loadCache() {
        Rectangle rectangle = new Rectangle();
        rectangle.setId("1");
        shapeMap.put(rectangle.getId(), rectangle);

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


        在这个示例中,Shape 是一个实现了 Cloneable 接口的抽象类,Rectangle 和 Square 是 Shape 的具体子类。ShapeCache 类负责存储和克隆原型对象。当需要一个新的 Shape 对象时,可以通过 ShapeCache.getShape 方法获取,这个方法会返回一个克隆的对象,而不是创建一个新的对象。

你可能感兴趣的:(设计模式,设计模式,原型模式)