原型模式比较简单,就是利用object中的clone()方法做一次深度拷贝,复制一份原有对象即可。这种方式的好处在于原有对象的拷贝没有调用原有对象的New方法,也就没有触发原有对象的构造函数链,提高了对象制造效率。这种模式应用场景在于对象基本相同,除了个别属性字段有区分,可以复制后更改这些个别字段即可。
原型模式类图:
[img]http://dl.iteye.com/upload/attachment/364528/11bc495e-d287-3be7-a23e-4737f5478cc6.jpg[/img]
具体实现demo:
原型类:
测试类:
说明:Cloneable接口这里本没有必要去实现,因为直接复写object中的clone方法就可以了。这里实现这个接口只是为了说明原型模式用的是深克隆。
原型模式类图:
[img]http://dl.iteye.com/upload/attachment/364528/11bc495e-d287-3be7-a23e-4737f5478cc6.jpg[/img]
具体实现demo:
原型类:
package protypePattern;
public class ProtoType implements Cloneable{
private String name;
private String content =" , welcome to Taobao,have fun here.";
public Object clone() {
Object o =null;
try{
o=(ProtoType)super.clone();
}catch(CloneNotSupportedException e) {
System.out.println(e.toString());
}
return o;
}
public void showGreetingwords(){
System.out.println(this.getName()+content);
}
public String getContent() {
return content;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
测试类:
package protypePattern;
public class PrototypePatternTest {
public static void main(String[] args){
ProtoType greetingForLxy = new ProtoType();
greetingForLxy.setName("lxy");
greetingForLxy.showGreetingwords();
System.out.println("-----------After cloning greetingForLxy---------");
ProtoType greetingForShuofeng = (ProtoType) greetingForLxy.clone();
greetingForShuofeng.setName("shuofeng");
greetingForShuofeng.showGreetingwords();
greetingForLxy.showGreetingwords();
}
}
说明:Cloneable接口这里本没有必要去实现,因为直接复写object中的clone方法就可以了。这里实现这个接口只是为了说明原型模式用的是深克隆。