菜鸟硕枫设计模式系列之5 原型模式
发布日期:2021-10-01 08:45:06 浏览次数:2 分类:技术文章

本文共 1452 字,大约阅读时间需要 4 分钟。

原型模式比较简单,就是利用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方法就可以了。这里实现这个接口只是为了说明原型模式用的是深克隆。

转载地址:https://blog.csdn.net/iteye_2655/article/details/81970358 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:菜鸟硕枫设计模式系列之6 建造者模式
下一篇:菜鸟硕枫设计模式系列之4 抽象工厂模式

发表评论

最新留言

很好
[***.229.124.182]2024年04月19日 06时47分53秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章