原型模式深入--使用序列化機制實現物件的深克隆
阿新 • • 發佈:2019-02-17
其實物件的深克隆還可以通過序列化來實現,直接上程式碼,物件使用的還是之前的sheep物件,但是要實現Serializable的介面:
public class Client3 {
public static void main(String[] args) throws CloneNotSupportedException, Exception {
Date date = new Date(12312321331L);
Sheep s1 = new Sheep("少利",date);
System.out.println(s1);
System.out .println(s1.getSname());
System.out.println(s1.getBirthday());
// 使用序列化和反序列化實現深複製
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(s1);
byte[] bytes = bos.toByteArray();
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bis);
Sheep s2 = (Sheep) ois.readObject(); //克隆好的物件!
System.out.println("修改原型物件的屬性值");
date.setTime(23432432423L);
System.out.println(s1.getBirthday());
s2.setSname("多利" );
System.out.println(s2);
System.out.println(s2.getSname());
System.out.println(s2.getBirthday());
}
}