原型模式十分简单和常用,当需要大量的 new 一个对象分别对不同对象进行属性赋值等操作时,可以使用原型模式来直接复制对象,而不去 new 一个个对象。因为 new 对象的过程,也是比较消耗资源的。而对象的克隆,是在内存二进制流的拷贝。
特别是要在一个循环体内产生大量的对象时,原型模式可以更好地体现其优点。同时,直接在内存中拷贝,构造函数是不会执行的。
// 一个具有众多属性的类
public class Document implements Cloneable{
@Override
protected Document clone(){
Document document = null;
try {
document = (Document) super.clone();
} catch (CloneNotSupportedException e) {
// TODO: handle exception
}
// TODO Auto-generated method stub
return document;
}
}
// 测试类
public class Test {
public static void main(String[] args){
Document document = new Document();
for(int i=0; i<10000; i++){
Document cloneDoc = document.clone();
// 对cloneDoc对象进行处理
}
}
}
这里,循环一万次每次都 new 一个大对象是很不划算的,可以使用对象的 clone 方法,直接复制出需要的对象。