什么是原型模式?
原型模式是指用原型实例创建对象种类,并且通过拷贝这些原型创建新的对象
原型模式结构图
prototype:原型类,声明一个克隆自己的接口
ConcretePrototype:具体的原型类,实现一个克隆自己的操作
Client:让一个对象克隆自己,从而创建一个新的对象
深拷贝和浅拷贝的问题
浅拷贝使用cloneable接口来实现
深拷贝通过重写cloneable方法或者对象序列化来实现(推荐序列化)
//创建流对象
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);
DeepProtoType copyObj = (DeepProtoType)ois.readObject();
return copyObj;
} catch (Exception e) {
// TODO: handle exception e.printStackTrace();
return null;
} finally {
//关闭流 try {
bos.close();
oos.close();
bis.close();
ois.close();
} catch (Exception e2) {
// TODO: handle exception System.out.println(e2.getMessage());
}
}