克隆模式
浅克隆:创建一个新对象,新对象的属性和原来对象完全相同,对于非基本类型属性,仍指向原有属性所指向的对象的内存地址。
深克隆:创建一个新对象,属性中引用的其他对象也会被克隆,不再指向原有对象地址。
创建原型类Monkey
import java.util.Date;
public class Monkey {
public int height;
public int weight;
public Date birthday;
}
创建引用对象JinGuBang
import java.io.Serializable;
/**
* @author Yin
* @date 2021/3/4 20:12
*/
public class JinGuBang implements Serializable {
public float h = 100;
public float d = 100;
public void big() {
this.d *= 2;
this.h *= 2;
}
public void small(){
this.d /= 2;
this.h /= 2;
}
}
创建具体的对象类QiTianDaSheng
import java.io.*;
import java.util.Date;
/**
* @author Yin
* @date 2021/3/4 20:15
*/
public class QiTianDaSheng extends Monkey implements Cloneable, Serializable {
public JinGuBang jinGuBang;
public QiTianDaSheng() {
this.birthday = new Date();
this.jinGuBang = new JinGuBang();
}
@Override
protected Object clone() throws CloneNotSupportedException {
return this.deepClone();
}
public Object deepClone() {
try {
// 将对象写到流里
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(this);
// 从流里读出来
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
QiTianDaSheng copy = (QiTianDaSheng) ois.readObject();
copy.birthday = new Date();
return copy;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public QiTianDaSheng shallowClone(QiTianDaSheng target) {
QiTianDaSheng qiTianDaSheng = new QiTianDaSheng();
qiTianDaSheng.height = target.height;
qiTianDaSheng.weight = target.weight;
qiTianDaSheng.jinGuBang = target.jinGuBang;
qiTianDaSheng.birthday = new Date();
return qiTianDaSheng;
}
}
测试代码
/**
* @author Yin
* @date 2021/3/4 20:42
*/
public class DeepCloneTest {
public static void main(String[] args) {
QiTianDaSheng qiTianDaSheng = new QiTianDaSheng();
try {
QiTianDaSheng clone = (QiTianDaSheng) qiTianDaSheng.clone();
System.out.println(clone.birthday);
System.out.println(qiTianDaSheng.birthday);
System.out.println(clone.birthday == qiTianDaSheng.birthday);
System.out.println("深克隆: " + (qiTianDaSheng.jinGuBang == clone.jinGuBang));
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
QiTianDaSheng q = new QiTianDaSheng();
QiTianDaSheng n = q.shallowClone(q);
System.out.println("浅克隆: " + (q.jinGuBang == n.jinGuBang));
}
}
测试结果:
参考文章链接:https://www.cnblogs.com/liqiangchn/p/9465186.html
参考书籍:《Spring 5核心原理与30个类手写实战》