基本介绍:
原型模式(Prototype):原型实例指定创建对象的种类,并且通过拷贝这些原型,创建新的对象
原型模式是一种创建型设计模式,允许一个对象再创建另一个可定制的对象,无需知道如何创建的细节
工作原理:在原型对象中,实现Clone接口,重写clone方法,其他对象需要创建多个原型对象时,可以使用对象.clone()
浅拷贝:
- 对于数据类型是基本数据类型的成员变量,浅拷贝会直接进行值传递,也就是将该属性值复制一份给新的对象
- 对于数据类型是引用数据类型的成员变量,比如说成员变量是某个数组,某个类的对象等,那么浅拷贝就会进行地址引用传递,也就是将成员变量的引用值(内存地址)复制一份给新的对象.因为实际上两个对象的该成员变量都指向同一个实例.在这种情况下,在一个对象中修改该成员变量会影响到另一个对象的该成员变量
深拷贝:
对整个对象进行拷贝,引用数据类型的成员变量,会申请存储空间
两种实现方法:
public class DeepCloneableTarget implements Serializable, Cloneable {
private static final long serialVersionUID = 1L;
private String cloneName;
private String cloneClass;
public DeepCloneableTarget(String cloneName, String cloneClass) {
this.cloneName = cloneName;
this.cloneClass = cloneClass;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public class DeepProtoType implements Serializable, Cloneable {
public String name;
public DeepCloneableTarget deepCloneableTarget;
public DeepProtoType() {
}
//深拷贝 方式1 clone
//对每一个引用类型的数据都要进行单独克隆
@Override
protected Object clone() throws CloneNotSupportedException {
Object deep = null;
//这里完成对基本数据类型的克隆
deep = super.clone();
//处理引用类型数据
DeepProtoType deepProtoType = (DeepProtoType)deep;
deepProtoType.deepCloneableTarget = (DeepCloneableTarget) deepCloneableTarget.clone();
return deepProtoType;
}
//深拷贝 方式2 通过对象的序列化实现
//将自身对象序列化后通过流的方式
public Object deepClone() throws IOException {
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 copy = (DeepProtoType) ois.readObject();
return copy;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
ois.close();
bis.close();
oos.close();
bos.close();
}
}
}
客户端
public class Client {
public static void main(String[] args) throws CloneNotSupportedException, IOException {
DeepProtoType deepProtoType = new DeepProtoType();
deepProtoType.name = "xx";
deepProtoType.deepCloneableTarget = new DeepCloneableTarget("cloneName", "CC");
//方式1
DeepProtoType clone1 = (DeepProtoType)deepProtoType.clone();
System.out.println(deepProtoType.deepCloneableTarget.hashCode());
System.out.println(clone1.deepCloneableTarget.hashCode());
//方式2
DeepProtoType p2 = (DeepProtoType)deepProtoType.deepClone();
System.out.println(p2.deepCloneableTarget.hashCode());
System.out.println(deepProtoType.deepCloneableTarget.hashCode());
}
}
注意事项
- 创建新的对象比较复杂时,可以利用原型模式简化对象的创建过程,同时也能提高效率
- 不用重写初始化对象,而是动态的获得对象运行时的状态
- 如果原始对象发生变化(添加或减少属性),其他克隆对象也会发生相应的变化,无需修改代码
缺点:
需要为每一个类配置一个克隆方法,对已有的类进行修改时,会改变源代码,违背了ocp原则