100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > 设计模式 原型模式_设计模式:原型

设计模式 原型模式_设计模式:原型

时间:2023-09-03 01:37:35

相关推荐

设计模式 原型模式_设计模式:原型

设计模式 原型模式

创新设计模式之一是原型设计模式。 尽管原型是创造模式,但它在概念上与其他模式有所区别。 我的意思是原型在某种意义上创造了自己。 我将在下面解释。

原型模式的所有魔力都基于Java Object的clone()方法。 因此,让我们考虑一个用法示例,然后我将尝试找出该模式的利弊。

上面的类图向我们展示了该模式的基本含义。 抽象类或接口可以充当原型的角色。 注意,原型必须扩展Cloneable接口。 这是因为原型的具体实现将调用clone()方法。 实现接口的特定类(扩展了抽象类)必须包含将在克隆操作的帮助下返回其自身副本的方法。

在我的示例中,我将Unicellular接口声明为原型,并将Amoeba类声明为其实现:

public interface Unicellular extends Cloneable {public Unicellular reproduce();}

public class Amoeba implements Unicellular {public Unicellular reproduce() {Unicellular amoeba = null;try {amoeba = (Unicellular) super.clone();} catch (CloneNotSupportedException e) {e.printStackTrace();}return amoeba;}public String toString() {return "Bla bla bla it's a new amoeba...";}}

示范:

...public static void main(String[] args) {Unicellular amoeba = new Amoeba();List< Unicellular > amoebaList = new ArrayList< Unicellular >();amoebaList.add(amoeba.reproduce());amoebaList.add(amoeba.reproduce());amoebaList.add(amoeba.reproduce());for (Unicellular a : amoebaList)System.out.println(a);}...

结果:

Bla bla bla it’s a new amoeba…Bla bla bla it’s a new amoeba…Bla bla bla it’s a new amoeba…

利弊如何? 实际上,我不知道该说些什么,因为我从未遇到过适当应用原型模式的情况。 也许在某些情况下,当您不需要显式调用构造函数或系统不需要依赖于对象创建方式时。

参考:设计模式:来自我们JCG合作伙伴 Alexey Zvolinskiy的原型 ,位于Fruzenshtein的注释博客中。

翻译自: //06/design-patterns-prototype.html

设计模式 原型模式

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。