创建型模式:05-原型模式
2021-06-11 本文已影响0人
综合楼
浅克隆
image.png深克隆
image.png示例代码:
import java.io.*;
public class Dog implements Cloneable, Serializable {
private static final long serialVersionUID = 1589397062304887365L;
String color;
Integer old;
Dog son;
Dog(String color, Integer old, Dog son){
this.color = color;
this.old = old;
this.son = son;
}
//浅克隆(ShallowClone)
@Override
public Dog clone() {
try {
return (Dog) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
return null;
}
}
//深克隆(DeepClone)
public Dog deepClone() {
//将对象写入流中
ByteArrayOutputStream bao=new ByteArrayOutputStream();
try(ObjectOutputStream oos= new ObjectOutputStream(bao)) {
oos.writeObject(this);
} catch (IOException e) {
e.printStackTrace();
}
//将对象从流中取出
try(ByteArrayInputStream bis=new ByteArrayInputStream(bao.toByteArray());
ObjectInputStream ois= new ObjectInputStream(bis)) {
return (Dog)ois.readObject();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
public class TestShallowClone {
public static void main(String[] args) {
Dog son = new Dog("red", new Integer(1),null);
Dog father = new Dog("black", new Integer(5), son);
Dog father2 = father.clone();
System.out.println(father==father2);
System.out.println(father.color==father2.color);
System.out.println(father.old==father2.old);
System.out.println(father.old.equals(father2.old));
System.out.println(father.son==father2.son);
}
}
image.png
public class TestDeepClone {
public static void main(String[] args) {
Dog son = new Dog("red", new Integer(1),null);
Dog father = new Dog("black", new Integer(5), son);
Dog father2 = father.deepClone();
System.out.println(father==father2);
System.out.println(father.color==father2.color);
System.out.println(father.old==father2.old);
System.out.println(father.old.equals(father2.old));
System.out.println(father.son==father2.son);
}
}
image.png