1、原型模式介绍
原型模式(Prototype Pattern)用于创建重复对象,通过当前对象的克隆可以节省创建复杂对象的时间,保证性能。
- 原型模式的实现方式比较简单,Java多数类中提供了相应的API方法:Object Clone()
- 对于需要实现原型模式的类只要实现Cloneable接口,默认调用Object的clone()的方法,该方法是浅拷贝,只会拷贝对象中的基本数据类型,对于数组、引用对象等是不会拷贝的,需要手动实现clone()方法去实现深拷贝。
2、代码实现
2.1、浅拷贝
public class SimplePrototype implements Cloneable{
private String type = "type";
private ArrayList<String> typeList = new ArrayList<>();
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public ArrayList<String> getTypeList() {
return typeList;
}
public void setTypeList(ArrayList<String> typeList) {
this.typeList = typeList;
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
2.2、深拷贝
public class DeepPrototype implements Cloneable{
private String type = "type";
private ArrayList<String> typeList = new ArrayList<>();
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public ArrayList<String> getTypeList() {
return typeList;
}
public void setTypeList(ArrayList<String> typeList) {
this.typeList = typeList;
}
@Override
public Object clone() throws CloneNotSupportedException {
DeepPrototype deepPrototype = (DeepPrototype)super.clone();
deepPrototype.typeList = (ArrayList<String>)typeList.clone();
return deepPrototype;
}
}
2.3、测试验证
- 测试代码
public class PrototypeTest {
public static void main(String[] args) throws CloneNotSupportedException{
//浅拷贝
SimplePrototype simplePrototype = new SimplePrototype();
System.out.println(simplePrototype.getType() + ";" + simplePrototype.getTypeList().toString());
SimplePrototype simplePrototypeClone = (SimplePrototype) simplePrototype.clone();
simplePrototypeClone.getTypeList().add("1");
System.out.println(simplePrototype.getType() + ";" + simplePrototype.getTypeList().toString());
System.out.println(simplePrototypeClone.getType() + ";" + simplePrototypeClone.getTypeList().toString());
//深拷贝
DeepPrototype deepPrototype = new DeepPrototype();
System.out.println(deepPrototype .getType() + ";" + deepPrototype .getTypeList().toString());
DeepPrototype deepPrototypeClone = (DeepPrototype) deepPrototype.clone();
deepPrototypeClone.getTypeList().add("2");
System.out.println(deepPrototype .getType() + ";" + deepPrototype .getTypeList().toString());
System.out.println(deepPrototypeClone .getType() + ";" + deepPrototypeClone .getTypeList().toString());
}
}
- 验证结果
3、总结
优点:通过克隆⽅式创建复杂对象、可以避免重复做初始化操作,创建复杂对象的时间,保证性能。
缺点:对象中引用了循环结构的克隆以及深度使用对象的克隆都会异常麻烦。