菜鸟硕枫设计模式系列之5 原型模式

原型模式比较简单,就是利用object中的clone()方法做一次深度拷贝,复制一份原有对象即可。这种方式的好处在于原有对象的拷贝没有调用原有对象的New方法,也就没有触发原有对象的构造函数链,提高了对象制造效率。这种模式应用场景在于对象基本相同,除了个别属性字段有区分,可以复制后更改这些个别字段即可。

原型模式类图:
[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方法就可以了。这里实现这个接口只是为了说明原型模式用的是深克隆。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值