设计模式之原型模式
# 设计模式之原型模式
# 一、简介
用于创建重复的对象,同时又能保证性能
当对象的创建非常复杂时,可以考虑使用原型模式快速创建对象
# 二、实现方式
# 1、浅克隆
需要实现Cloneable
接口。克隆一个新对象,但是属性中引用的其他对象不会被克隆,仍然指向原有对象地址
public class MacBook implements Cloneable {
private String name;
@Override
protected MacBook clone() throws CloneNotSupportedException {
return (MacBook) super.clone();
}
}
1
2
3
4
5
6
7
2
3
4
5
6
7
# 2、深克隆
需要实现Serializable
接口。克隆一个新对象,属性中引用的其他对象也会被克隆,不再指向原有对象地址。
public class MacBook implements Cloneable, Serializable {
private String name;
@Override
protected MacBook clone() {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(this);
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
return (MacBook) ois.readObject();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17