设计模式 | 原型模式

159 阅读1分钟

定义

使用原型实例指定创建对象的类型,通过复制原型实例创建新的对象。

使用场景

  • 创建一个对象的成本较高。
  • 一个对象可能被多个使用者修改,通过复制实现保护性拷贝。

Java 代码示例

  • 浅拷贝
public class Doc implements Cloneable {
    
    private String text;
    private ArrayList<String> images = new ArrayList<>();

    @Override
    protected Doc clone() {
        Doc doc = null;
        try {
            doc = (Doc) super.clone();
            doc.text = text;
            doc.images = images;
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return doc;
    }
}
  • 深拷贝
public class Doc implements Cloneable {

    private String text;
    private ArrayList<String> images = new ArrayList<>();

    @Override
    protected Doc clone() {
        Doc doc = null;
        try {
            doc = (Doc) super.clone();
            doc.text = text;
            doc.images = (ArrayList<String>) images.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return doc;
    }
}
  • 使用
Doc doc = new Doc();
Doc cloneDoc = doc.clone();