原型模式(Prototype Pattern)的简单程度仅次于单例模式和迭代器模式。正是由于简
单,使用的场景才非常地多,其定义如下:
Specify the kinds of objects to create using a prototypical instance,and create new objects by
copying this prototype.(用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对
单,使用的场景才非常地多,其定义如下:
Specify the kinds of objects to create using a prototypical instance,and create new objects by
copying this prototype.(用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对
象。)
public class PrototypeClass implements Cloneable{
//覆写父类Object方法
@Override
public PrototypeClass clone(){
PrototypeClass prototypeClass = null;
try {
prototypeClass = (PrototypeClass)super.clone();
} catch (CloneNotSupportedException e) {
//异常处理
}
return prototypeClass;
}
}
● 性能优良
原型模式是在内存二进制流的拷贝,要比直接new一个对象性能好很多,特别是要在一
个循环体内产生大量的对象时,原型模式可以更好地体现其优点。
● 逃避构造函数的约束
这既是它的优点也是缺点,直接在内存中拷贝,构造函数是不会执行的(参见13.4
节)。优点就是减少了约束,缺点也是减少了约束,需要大家在实际应用时考虑。