原型模式(Prototype)以及深浅复制

5、原型模式(Prototype)

view plaincopy
    public class Prototype implements Cloneable {  
  1.   
  2.     public Object clone() throws CloneNotSupportedException {  
  3.         Prototype proto = (Prototype) super.clone();  
  4.         return proto;  
  5.     }  
  6. }  

浅复制:将一个对象复制后,基本数据类型的变量都会重新创建,而引用类型,指向的还是原对象所指向的。

此处,写一个深浅复制的例子:

    public class Prototype implements Cloneable, Serializable {  
  1.   
  2.     private static final long serialVersionUID = 1L;  
  3.     private String string;  
  4.   
  5.     private SerializableObject obj;  
  6.   
  7.     /* 浅复制 */  
  8.     public Object clone() throws CloneNotSupportedException {  
  9.         Prototype proto = (Prototype) super.clone();  
  10.         return proto;  
  11.     }  
  12.   
  13.     /* 深复制 */  
  14.     public Object deepClone() throws IOException, ClassNotFoundException {  
  15.   
  16.         /* 写入当前对象的二进制流 */  
  17.         ByteArrayOutputStream bos = new ByteArrayOutputStream();  
  18.         ObjectOutputStream oos = new ObjectOutputStream(bos);  
  19.         oos.writeObject(this);  
  20.   
  21.         /* 读出二进制流产生的新对象 */  
  22.         ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());  
  23.         ObjectInputStream ois = new ObjectInputStream(bis);  
  24.         return ois.readObject();  
  25.     }  
  26.   
  27.     public String getString() {  
  28.         return string;  
  29.     }  
  30.   
  31.     public void setString(String string) {  
  32.         this.string = string;  
  33.     }  
  34.   
  35.     public SerializableObject getObj() {  
  36.         return obj;  
  37.     }  
  38.   
  39.     public void setObj(SerializableObject obj) {  
  40.         this.obj = obj;  
  41.     }  
  42.   
  43. }  
  44.   
  45. class SerializableObject implements Serializable {  
  46.     private static final long serialVersionUID = 1L;  
  47. }  
 
要实现深复制,需要采用流的形式读入当前对象的二进制输入,再写出二进制数据对应的对象。
原文地址:https://www.cnblogs.com/skyball/p/5463382.html