hooyantsing's Blog

P52 原型模式(4)-深拷贝

字数统计: 438阅读时长: 2 min
2020/11/09

尚硅谷Java设计模式(图解+框架源码剖析)

深拷贝实现方式两种

  1. 重写clone()方法实现
  2. 通过对象序列化实现
1. 重写clone()方法实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Sheep implements Cloneable{
private String name;
private int age;
private String color;
private Human farmer;

@Override
protected Object clone() throws CloneNotSupportedException {
// 1.先拷贝自身的基础类型的成员变量
Sheep sheep = (Sheep)super.clone();
// 2.再拷贝自身的引用类型的成员变量
sheep.setFarmer((Human) this.farmer.clone());
return sheep;
}

// getter setter toSting
}
1
2
3
4
5
6
7
8
9
10
public class Human implements Cloneable{
private String name;

@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}

// getter setter toSting
}

测试:

1
2
3
4
5
6
7
8
9
public class Test{
public static void main(String[] args) throws CloneNotSupportedException {
Sheep sheep = new Sheep("tom",1,"白色");
sheep.setFarmer(new Human("hooy"));
Sheep sheepClone = (Sheep)sheep.clone();
System.out.println(sheep.getFarmer() == sheepClone.getFarmer());
System.out.println("sheep:" + sheep.getFarmer().hashCode() + " //sheepClone:" + sheepClone.getFarmer().hashCode());
}
}

执行结果:

false
sheep:1163157884 //sheepClone:1956725890

2. 通过对象序列化实现

原生写法:(建议直接使用第三方库的序列化/反序列化,如:jackson、fastjson和gson)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
public class Sheep implements Cloneable, Serializable {
private String name;
private int age;
private String color;
private Human farmer;

@Override
protected Object clone() throws CloneNotSupportedException {
/*
// 1.先拷贝自身的基础类型的成员变量
Sheep sheep = (Sheep)super.clone();
// 2.再拷贝自身的引用类型的成员变量
sheep.setFarmer((Human) this.farmer.clone());
return sheep;
*/
ByteArrayOutputStream bos = null;
ObjectOutputStream oos = null;
ByteArrayInputStream bis = null;
ObjectInputStream ois = null;
try {
// 序列化
bos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(bos);
oos.writeObject(this);

// 反序列化
bis = new ByteArrayInputStream(bos.toByteArray());
ois = new ObjectInputStream(bis);
return ois.readObject();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
return null;
} finally {
try {
if (bos != null) {
bos.close();
}
if (oos != null) {
oos.close();
}
if (bis != null) {
bis.close();
}
if (ois != null) {
ois.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

测试:

执行结果:

false
sheep:2125039532 //sheepClone:764977973

CATALOG
  1. 1. 深拷贝实现方式两种
    1. 1.1. 1. 重写clone()方法实现
    2. 1.2. 2. 通过对象序列化实现