《修炼Java开发技术:在架构中体验设计模式和算法之美》
原型模式 通用源代码:
public class PrototypeClass implements Cloneable {
@Override
public PrototypeClass clone(){
PrototypeClass prototypeClass = null;
try {
prototypeClass = (PrototypeClass)super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return prototypeClass;
}
}
使用序列化技术实现深拷贝:
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class PrototypeClass implements Serializable {
private static final long serialVersionUID = 1L;
//使用序列化技术实现深拷贝
public PrototypeClass deepClone() throws IOException, ClassNotFoundException{
//将对象写入流中
ByteArrayOutputStream bao = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bao);
oos.writeObject(this);
//将对象从流中取出
ByteArrayInputStream bis = new ByteArrayInputStream(bao.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
return (PrototypeClass)ois.readObject();
}
}