相关文章
【合集】Java设计模式
涉及角色
抽象原型
具体原型
使用场景
对象的创建非常复杂,可以使用原型模式快捷的创建对象。
性能和安全要求比较高。
原型类
Citation实现抽象原型Cloneable
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
@Getter
@Setter
@NoArgsConstructor
public static class Citation implements Cloneable, Serializable {
private Student student;
@Override
protected Citation clone() throws CloneNotSupportedException {
return (Citation) super.clone();
}
}
@NoArgsConstructor
public static class Student implements Serializable {
}
|
浅克隆
外部类是新的对象,内部类保留原引用
1
2
3
4
5
6
7
8
9
|
Citation citation = new Citation();
Student student = new Student();
citation.setStudent(student);
// 浅克隆
Citation citation1 = citation.clone();
System.out.println(citation == citation1); // false
System.out.println(citation.getStudent() == citation1.getStudent()); // true
|
深克隆
外部类和内部类都是新的对象
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
Citation citation = new Citation();
Student student = new Student();
citation.setStudent(student);
// 深克隆
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(原型模式.class.getResource("/").getPath() + "test" + File.separator + "b.txt"));
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(原型模式.class.getResource("/").getPath() + "test" + File.separator + "b.txt"));
oos.writeObject(citation);
Citation citation2 = (Citation) ois.readObject();
oos.close();
ois.close();
System.out.println(citation == citation2); // false
System.out.println(citation.getStudent() == citation2.getStudent()); // false
|