1.从Prototype设计模式说起
在设计模式中会规避使用具体类通过new方法创建实例对象,这是为了规避针对具体编程。因此,会有诸如抽象工厂或者prototype模式来创建实例对象。其中,prototype实际上就是通过Object中的native方法clone(),实现将实例对象中的所有字段值直接复制到新的实例之中。
一般是如下形式,实现Clonable接口,然后覆写clone方法,并直接调用父类clone方法,就是调用到Object中native的clone方法。
class CloneObject implements Cloneable {
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
//Object.java
public class Object {
......
protected native Object clone() throws CloneNotSupportedException;
}
2.从浅拷贝到深拷贝的问题
Object提供的clone方法,是一种浅拷贝实现方式,一旦字段本身就是引用类型,那么就会出现克隆对象和原对象在该字段是引用的同一个引用对象的问题。
如下,如果字段就是自定义类型,此时克隆对象和初始对象实际上在该字段上引用的是同一个对象。如果,其中一个修改了该字段的属性,如把deepCopy对象的name属性修改了,那么两个对象其实都会修改的。
class CloneObject implements Cloneable {
private Integer age;
private String name;
private DeepCopy deepCopy; //浅拷贝,引用类型会是相同对象在堆空间上
public CloneObject(int age, String name) {
this.age = age;
this.name = name;
this.deepCopy = new DeepCopy(age, name);
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
class DeepCopy implements Serializable{
private int age;
private String name;
public DeepCopy(int age, String name) {
this.age = age;
this.name = name;
}
}
3.深拷贝的解决方案
- 半解决方案:通过不断对于引用对象使用clone,最终组合成完整的深拷贝对象。毕竟对象的属性最终都是有基本数据类型组成的。
- 完整解决方案:通过序列化和反序列化的操作,实现对象的完整拷贝。
public class TestClone {
public static void main(String[] args){
System.out.println("execute begin");
for (String arg : args) {
System.out.print("arg : " + arg);
}
System.out.println("execute begin");
CloneObject cloneObject = new CloneObject(123, "first");
CloneObject clone = null;
//1.通过clone方法实现的prototype模式,浅拷贝
try {
clone = (CloneObject)cloneObject.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
//2.通过序列号和反序列化实现深拷贝
//clone = SerializableUtil.clone(cloneObject);
System.out.println(cloneObject + " , " + clone);
System.out.println(String.format("first hash %s and second hash %s", cloneObject.hashCode(), clone.hashCode()));
clone.setAge(234);
clone.getDeepCopy().setName("deepcopy");
System.out.println(cloneObject + " , " + clone);
}
}
class CloneObject implements Cloneable , Serializable{
private Integer age;
private String name;
private DeepCopy deepCopy;
public CloneObject(int age, String name) {
this.age = age;
this.name = name;
this.deepCopy = new DeepCopy(age, name);
}
public void setAge(int age) {
this.age = age;
}
public void setName(String name) {
this.name = name;
}
public DeepCopy getDeepCopy() {
return deepCopy;
}
@Override
protected Object clone() throws CloneNotSupportedException {
//1.修改后的clone也可以针对一层引用对象实现深拷贝
/*CloneObject cloneObject = (CloneObject) super.clone();
cloneObject.deepCopy = (DeepCopy) deepCopy.clone();
return cloneObject;*/
//2.常规clone,其实就是浅拷贝
return super.clone();
}
@Override
public String toString() {
return "CloneObject{" +
"age=" + age +
", name='" + name + '\'' +
", deepCopy=" + deepCopy +
'}';
}
}
class DeepCopy implements Cloneable, Serializable{
private int age;
private String name;
public DeepCopy(int age, String name) {
this.age = age;
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void setName(String name) {
this.name = name;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
@Override
public String toString() {
return "DeepCopy{" +
"age=" + age +
", name='" + name + '\'' +
'}';
}
}
class SerializableUtil {
public static <T extends Serializable> T clone(T obj) {
T cloneObj = null;
try {
// 写入字节流
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream obs = new ObjectOutputStream(out);
obs.writeObject(obj);
obs.close();
// 分配内存,写入原始对象,生成新对象
ByteArrayInputStream ios = new ByteArrayInputStream(out.toByteArray());
ObjectInputStream ois = new ObjectInputStream(ios);
// 返回生成的新对象
cloneObj = (T) ois.readObject();
ois.close();
} catch (Exception e) {
e.printStackTrace();
}
return cloneObj;
}
}