1.4(设计模式)原型模式

原型模式,通过拷贝创建好的实例对象来创建对象,用于创建重复的对象,同时保持性能。 

先将Shpae抽象类实现Cloneable接口,重写clone方法,用于克隆对象。

Circle类继承Shape抽象类。

ShapeCache中的load方法创建实例,并将实例放入HashMap。

后续获取对象,通过对象的key从HashMap中获取对象,并调用clone方法返回拷贝对象。

Shape抽象类,实现clone方法,克隆对象。

public abstract class Shape implements Cloneable{
    private String id;
    protected String type;    
    
    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 abstract void draw();
        
    @Override
    protected Shape clone() throws CloneNotSupportedException {
        // TODO Auto-generated method stub
        return (Shape) super.clone();
    }
}

 Circle  ,Shape的子类

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

 ShapeCache用于加载实例、获取对象并返回其克隆对象。

import java.util.HashMap;
import java.util.Map;

public class ShapeCache {
    private static Map<String,Shape> shapeCache = new HashMap<String,Shape>();
    
    public static Shape getShape(String id) throws CloneNotSupportedException {
        return shapeCache.get(id).clone();
    }
    
    public static void loadShape() {
        Shape circle = new Circle();
        circle.setId("1");
        shapeCache.put(circle.getId(), circle);
    }
}

 测试:

public class Main {

    public static void main(String[] args) throws CloneNotSupportedException {
        ShapeCache.loadShape();
        Shape circle = ShapeCache.getShape("1");
        circle.draw();
        System.out.println(circle.type);
    }
}
运行结果:
draw circle
circle

参考资料:

详解Java中的clone方法 — 原型模式

原文地址:https://www.cnblogs.com/huang-changfan/p/10725975.html