设计模式---原型模式

1.定义

原型模式:用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。

简单来说,原型模式就是将需要耗费较多资源的对象(原型对象)存储在缓存中,当用户需要使用到这些原型对象的时候,程序就从缓存中获取到它并进行克隆得到一个与原型对象一样的新对象,再将其克隆的新对象返回给用户。原型模式的好处在于提高了性能,采用以空间换取时间的思想。

2.案例

/**
 * 形状抽象类
 */
public abstract class Shape implements Cloneable {

    private String id;
    protected String type;

    public abstract void draw();

    public String getId() {
        return id;
    }

    public void setId(String 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 Rectangle extends Shape {

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

    @Override
    public void draw() {
        System.out.println("This is Rectangle: draw()...");
    }

}
/**
 * 圆形类
 */
public class Circle extends Shape {

    public Circle() {
        type = "circle";
    }

    @Override
    public void draw() {
        System.out.println("This is Circle: draw()...");
    }

}
/**
 * 正方形类
 */
public class Square extends Shape {

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

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

}
/**
 * 缓存类,用于存储原型对象(被克隆的对象)
 */
public class ShapeCache {

    private static Map<String, Shape> shapeMap = new HashMap<>();

    //从缓存中获取原型对象
    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);

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

}
public class PrototypePatternDemo {

    public static void main(String[] args) {
        ShapeCache.loadCache();

        Shape clonedShape = ShapeCache.getShape("1");
        System.out.println("Shape : " + clonedShape.getType());

        Shape clonedShape2 = ShapeCache.getShape("2");
        System.out.println("Shape : " + clonedShape2.getType());

        Shape clonedShape3 = ShapeCache.getShape("3");
        System.out.println("Shape : " + clonedShape3.getType());
    }

}

猜你喜欢

转载自blog.csdn.net/Blue_Sky2015/article/details/83782521