学过设计模式的都知道原型模式有两种形式,深拷贝和浅拷贝,其中的深拷贝又分了两种实现方式
方式一:重写clone方法
方式二:通过对象序列化来实现
今天就来说一下这第二种方式中的序列化。
先来看一下代码实现:
要复制类:
public class DeepProtoType implements Serializable{
public String name;
public DeepCloneableTarget deepCloneableTarget;//引用类型
public Object deepClone(){
//创建输出流对象
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){
e.printStackTrace();
}finally {
//关闭流
try {
bos.close();
oos.close();
bis.close();
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}
客户端:
DeepProtoType p=new DeepProtoType();
DeepPrototype pClone=(DeepProtoType)p.deepClone();
理解一下序列化,反序列化
序列化:将对象转换为字节序列存入磁盘
反序列化:将字节序列恢复为对象(这个对象是一个全新的对象)
序列化实现:需要该类实现Serializable接口,该类才可以被序列化
补充:实现Serializable接口的时候 IDEA会给出提醒,添加代码——private static final long serialVersionUID=1L;(什么作用读者自己去了解一下吧)
Spring框架原型模式的使用场景:<bean id="+" class="com.calculation.add" scope="prototype"></bean>
通过bean去创建对象的一种方式是通过原型模式去创建,在此就不多介绍了,想学习的可以去看spring源码了。