一.原型模式的概念
原型模式(Prototype Pattern)指使用原型实例指定待创建对象的类型,并且通过复制这个原型来创建新的对象。原型模式本身没有太多可说的内容,接下来更多的着眼于如何在java中做浅拷贝和深拷贝。
二.浅拷贝
浅拷贝指在复制时把成员类型中基本数据类型复制一份给新对象,但成员类型中引用类型只会复制地址给新对象(也就是说引用类型的成员在复制后被新旧对象所共用)。实现浅拷贝的一种优雅的方式是继承java的Cloneale接口,然后使用Object类自带的clone()方法,代码如下:
public class Prototype implements Cloneable{public Prototype clone(){Object object = null;try{object = super.clone();}catch(CloneNotSupportedException e){e.printTrace();}return (Prototype)object;}}
同时也可以通过定义Prototype为参数的构造方法来实现拷贝,比较简单就不列代码了。
三.深拷贝
深拷贝主要目的在于把引用类型的成员变量也复制一份给新对象。我们可以通过重写原型类及其所有成员类的clone()方法来实现深拷贝。
成员类:
public class Property implements Cloneable{public Property clone(){Object object = null;try{object = super.clone();}catch(CloneNotSupportedException e){e.printTrace();}return (Property)object;}}
原型类:
public class Prototype implements Cloneable{Property property;//...set and getpublic Prototype clone(){Object object = null;try{object = super.clone();}catch(CloneNotSupportedException e){e.printTrace();}Prototype p = (Prototype)object;p.property=p.getProperty().clone();retutn p;}}
这种方式需要实现所有相关类的clone()方法,稍显麻烦,java中更常用的深拷贝方式是通过**序列化**。首先让相关类继承Serializable接口。<br />
public class Property implements Serializable{}public class Prototype implements Serializable{Property property;//...}
把类转化成二进制字节码,之后通过读取这个字节码就可以拷贝原对象。
public class DeepCopyBySerialization {public static void main(String[] args) throws IOException, ClassNotFoundException {Prototype p1=new Prototype();//通过序列化方法实现深拷贝ByteArrayOutputStream bos=new ByteArrayOutputStream();ObjectOutputStream oos=new ObjectOutputStream(bos);oos.writeObject(p);oos.flush();ObjectInputStream ois=new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));Prototype p2=(Prototype)ois.readObject();}}
对于不想被序列化的成员可以用transient修饰。
