您的位置:首页 > 其它

设计模式 - 创建型模式 - 原型模式

2015-11-23 20:27 429 查看

浅度克隆

实现 Cloneable 接口

class ConcretePrototype implements Cloneable {
......
public ConcretePrototype clone() {
Object object = null;
try {
object = super.clone();
} catch (CloneNotSupportedException exception) {
System.err.println("Not support cloneable");
}
return (ConcretePrototype) object;
}
......
}


深度克隆

  实现 Serializable 接口

class WeeklyLog implements Serializable {
//使用序列化技术实现深克隆
public WeeklyLog deepClone() throws IOException, ClassNotFoundException, OptionalDataException {
//将对象写入流中
ByteArrayOutputStream bao = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bao);
oos.writeObject(this);
//将对象从流中取出
ByteArrayInputStream bis = new ByteArrayInputStream(bao.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
return (WeeklyLog) ois.readObject();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息