前言

Github:https://github.com/HealerJean

博客:http://blog.healerjean.com

1、复制模式

当创建对象的代价比较大的时候,采用这种模式,获取全新对象,ShapeCache用于创建和克隆 clone 复制实例对象

1.1、解释

1.1.1、备忘录模式和复制模式的区别

1、原型模式:解决的是创建对象的代价比较大的时候,保存的是当前对象的所有状态信息,恢复的时候会生成与保存的对象完全相同的另外一个实例;

2、备忘录模式用于保存和恢复对象的状,备忘录模式保存的是我们关心的在恢复时需要的对象的部分状态信息,相当于快照。。

1.2、示例代码

1.2.1、被复制的抽象对象

@Data
@ToString
public abstract class Shape implements Cloneable {

    public  String id;
    public  String type;

    abstract void draw();

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

1.2.2、子类

1.2.2.1、Rectangle extends Shape

@Data
@ToString
public class Rectangle extends Shape {

    private String pectangleName ;

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

    @Override
    public void draw() {
        System.out.println(id+":"+type+":"+pectangleName);
    }
}

1.2.2.2、Square extends Shape

@Data
@ToString
public class Square extends Shape {

    private String squareName ;

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

    @Override
    public void draw() {
        System.out.println(id+":"+type+":"+squareName);
    }
}

2.3、创建和复制的类ShapeCache

ShapeCache用于创建和克隆 clone 复制实例对象

public class ShapeCache {

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

    /**
     * 通过map和拷贝 获取全新对象
     */
    public static Shape getByType(String shapeId) {
        Shape cachedShape = shapeMap.get(shapeId);
        return (Shape) cachedShape.clone();
    }

    /**
     * 创建原型
     */
    public static void create(Shape shape) {
        shapeMap.put(shape.getType(),shape);
    }
}

2.4、测试

public class Main {

    public static void main(String[] args) {

        Rectangle rectangle = new Rectangle();
        rectangle.setType("rectangle");
        rectangle.setId("1");
        rectangle.setPectangleName("rectangleName");
        ShapeCache.create(rectangle);
        Square square = new Square();
        square.setType("square");
        square.setId("2");
        square.setSquareName("squareName");
        ShapeCache.create(square);

        rectangle = (Rectangle)ShapeCache.getByType("rectangle") ;
        rectangle.draw();
        square =    (Square)ShapeCache.getByType("square") ;
        square.draw();

    }


    // 1:rectangle:rectangleName
    // 2:square:squareName
}