Repository navigation
Expand file tree
/
Copy pathSheep.java
More file actions
90 lines (75 loc) · 1.94 KB
/
Copy pathSheep.java
File metadata and controls
90 lines (75 loc) · 1.94 KB
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package designMode.a05_Prototype;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
/**
* 若要使用clone方法必须要实现Clonneable接口,以达到标记的作用,不然会报CloneNotSupportedException
*/
public class Sheep implements Cloneable,Serializable{
private String name;
private ArrayList<String> stuff;
public Sheep(String name, ArrayList<String> stuff) {
super();
this.name = name;
this.stuff = stuff;
}
public Sheep(){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public Sheep clone(){
Sheep obj = null;
try {
obj = (Sheep) super.clone();
} catch (Exception e) {
e.printStackTrace();
}
return obj;
}
//深度复制
public Sheep deepClone(){
Sheep obj = null;
try {
obj = (Sheep) super.clone();
obj.stuff = (ArrayList<String>) this.stuff.clone(); //深度复制
} catch (Exception e) {
e.printStackTrace();
}
return obj;
}
//通过序列化克隆
public Sheep cloneBySerial(){
Sheep obj = null;
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(this);
byte[] bytes = bos.toByteArray();
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bis);
obj = (Sheep) ois.readObject(); //克隆好的对象!
} catch (Exception e) {
e.printStackTrace();
}
return obj;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ArrayList<String> getStuff() {
return stuff;
}
public void setStuff(ArrayList<String> stuff) {
this.stuff = stuff;
}
}