设计模式5-原型模式

定义

原型模式是利用一个已有的原型对象,快速生成和原型对象一样的实例

实现

浅克隆

比较简单的实现方式是使用cloneable接口。

但是克隆接口是一个空方法,如果不实现,会抛出异常

一般实现clone接口是类似于如下的方式

1
2
3
4
5
6
7
8
9
10
public class Student implement Cloneable{
private String name;
private int age;
private String sex;
@Override
protected Student clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
return (Student)super.clone();;
}
}

类似于这样,就可以实现Student类的克隆了。

但是这个只是很简单的一种克隆方式,如果学生类中有实体类的话,则不行,会同时共享该实体。

因此就叫浅克隆

深克隆

深克隆使用clone这个方法也是可以实现的,就是每个实体类都需要复写clone方法,然后赋给该饮用。相对来讲比较蛋疼。

还有一种深克隆的方式,是通过字节流来做。

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
@Override
protected Student clone(){
Student student = null;
// 使用序列化实现深克隆
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(this);// 将对象写入到字节数组中
oos.close(); // 关闭流
} catch (IOException e) {
e.printStackTrace();
}

ByteArrayInputStream bas = new ByteArrayInputStream(bos.toByteArray());
try {
ObjectInputStream ois = new ObjectInputStream(bas);// 从字节数组中读取对象
try {
student = (Student)ois.readObject();
ois.close(); // 关闭流
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
return student;
}

这样生成的对象,其内存地址都是不同的,引用的内存地址也是不同的。

序列化方便编写,但是差别是,其效率较低。如果方便的情况下,尽量使用复制域的方式进行