-
定义
用原型实例指定创建对象的种类,并通过拷贝这些原型创建新的对象。
-
使用场景
原型模式被用在频繁调用且极其相似的对象上,它会克隆对象并设置改变后的属性,而且消耗的资源较少。
-
代码举例实现
ProtoTypeImpl.java
package com.design.prototype;
public class ProtoTypeImpl implements Cloneable{
private int shallowClone;
private DeepClone deepClone = new DeepClone();
public ProtoTypeImpl() {
System.out.println("construct is called");
}
public void print() {
// TODO Auto-generated method stub
System.out.println(shallowClone);
System.out.println(deepClone.getS());
}
@Override
protected ProtoTypeImpl clone(){
// TODO Auto-generated method stub
try{
ProtoTypeImpl protoTypeImp = (ProtoTypeImpl) super.clone();
//protoTypeImp.shallowClone = this.shallowClone;
//protoTypeImp.deepClone = this.deepClone.clone();
return protoTypeImp;
}catch(Exception e){
e.printStackTrace();
return null;
}
}
public void setShallowClone(int shallowClone) {
this.shallowClone = shallowClone;
}
public void setS(String s){
deepClone.setS(s);
}
}
DeepClone.java
package com.design.prototype;
public class DeepClone implements Cloneable{
private String s;
public String getS() {
return s;
}
public void setS(String s) {
this.s = s;
}
@Override
protected DeepClone clone(){
// TODO Auto-generated method stub
try {
return (DeepClone)super.clone();
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
App.java
package com.design.prototype;
public class App {
public static void main(String[] args) {
// TODO Auto-generated method stub
ProtoTypeImpl protoTypeImp = new ProtoTypeImpl();
protoTypeImp.setShallowClone(1);
protoTypeImp.setS("deep clone");
protoTypeImp.print();
System.out.println("-------------");
ProtoTypeImpl protoTypeImp2 = protoTypeImp.clone();
protoTypeImp2.setShallowClone(2);
protoTypeImp2.setS("deep clone 2");
protoTypeImp2.print();
System.out.println("-------------");
protoTypeImp.print();
}
}
-
结果分析
运行结果1.png
这个现象主要是由于深浅复制引起的,普通类型的数据没有问题,而对象类型则有问题。同时我们应该注意到clone的时候构造函数是不会被调用的。
-
去掉ProtoTypeImpl.clone的两行注释(第一行没什么所谓,但是还是加上,有个对比)
运行结果2.png
-
总结优缺点
- 优点
原型模式是在内存二进制流的拷贝,要比直接 new 一个对象性能好很多,特别是要在一个循环体内产生大量的对象时,原型模式可以更好地体现其点。 - 缺点
使用过程中要切记构造函数不会被调用,所以在构造函数完成的操作应该多加处理,还有深浅复制的问题