- 原型模式(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;
}
}
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