Skip to content

Latest commit

 

History

History
117 lines (82 loc) · 2.39 KB

原型模式.md

File metadata and controls

117 lines (82 loc) · 2.39 KB

原型模式

  • 原型模式(Prototype Pattern)是用于创建重复的对象,同时又能保证性能
  • 核心接口 java.lang.Cloneable

编码

  • 一个标记类
public class Tag implements Serializable {

    private static final long serialVersionUID = -1732973065571551933L;
    public String f;

    public Tag(String f) {
        this.f = f;
    }


}
  • 原型类, 主要通过实现 clone 方法
public class Prototype implements Cloneable, Serializable {


    private static final long serialVersionUID = -2616767906128391875L;
    public String name;
    public Tag tag;

    public Prototype() {
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
    
}

测试用例

  • 主要测试值引用
public class PrototypeTest {

    public static void main(String[] args) throws Exception {
        Prototype prototype = new Prototype();
        prototype.name = "张三";
        prototype.tag = new Tag("123");

        Prototype clone = (Prototype) prototype.clone();

        clone.tag.f = "asasas";
        System.out.println(clone.tag.f);
        System.out.println(prototype.tag.f);

        System.out.println(clone.tag);
        System.out.println(prototype.tag);

        System.out.println(prototype.name == clone.name);
        System.out.println(prototype.tag == clone.tag);


    }

}
  • 输出结果
asasas
123
com.huifer.design.prototype.Tag@52cc8049
com.huifer.design.prototype.Tag@2b193f2d
false
false
  • 如果需要值引用相同则应该对 clone 方法进行修改, 变成深度拷贝, 复写的 clone , super.clone() 是浅拷贝. 深拷贝代码如下
    public Object deepClone() {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(this);

            ByteArrayInputStream bis = new ByteArrayInputStream(baos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bis);

            Prototype copyObject = (Prototype) ois.readObject();
            return copyObject;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
  • 执行结果
asasas
asasas
com.huifer.design.prototype.Tag@6e0be858
com.huifer.design.prototype.Tag@6e0be858
true
true