原型模式
深拷贝 浅拷贝
public class CloneTest implements Cloneable{
String name;
public CloneTest(String name) {
this.name = name;
}
@Override
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode())+"CloneTest{" +
"name=‘" + name + ‘\‘‘ +
‘}‘;
}
@Override
protected CloneTest clone() throws CloneNotSupportedException {
return (CloneTest) super.clone();
}
}
public class CloneObject implements Cloneable{
String name;
Integer age;
CloneTest cloneTest;
public CloneObject(String name, Integer age, CloneTest cloneTest) {
this.name = name;
this.age = age;
this.cloneTest = cloneTest;
}
@Override
public String toString() {
return "CloneObject{" +
"name=‘" + name + ‘\‘‘ +
", age=" + age +
", cloneTest=" + cloneTest +
‘}‘;
}
//深拷贝实现
@Override
protected Object clone() throws CloneNotSupportedException {
//方式一
CloneObject cloneObject = (CloneObject)super.clone();
CloneTest cloneTest = this.cloneTest.clone();
cloneObject.cloneTest=cloneTest;
return cloneObject;
//方式二 使用oos ObjectOutputStream()
}
public static void main(String[] args) {
CloneTest cloneTest =new CloneTest("test");
CloneObject cloneObject = new CloneObject("花花",12,cloneTest);
try {
Object clone = cloneObject.clone();
System.out.println(cloneObject);
//默认是浅拷贝
//CloneTest cloneTest;为同一个地址 改变 cloneTest内参数 导致clone也会被改变
cloneObject.cloneTest.name="hh";
System.out.println(clone);
// CloneObject{name=‘花花‘, age=12, cloneTest=com.build.CloneTest@4554617cCloneTest{name=‘test‘}}
// CloneObject{name=‘花花‘, age=12, cloneTest=com.build.CloneTest@4554617cCloneTest{name=‘hh‘}}
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}