【问题标题】:How to use prototype pattern with correct meaning?如何正确使用原型模式?
【发布时间】:2016-03-09 15:11:11
【问题描述】:

我正在尝试理解原型设计模式。

这里是示例代码。

public class App {
    public static void main(String[] args) {


        //Prototype proto = new Prototype();

        Dog d = new Dog();

        Dog clone ;//= (Dog)proto.getClone(d);

        clone = (Dog) d.makeCopy();

        System.out.println(d);
        System.out.println(clone);
        System.out.println("xxxxxxxxxxxxxx");

        //System.out.println();
        //d.setval("test");
        //System.out.println(clone.getVal());

    }
}

很清楚如何在原型中创建狗的克隆。

Dog d = new Dog();
Dog clone ;
clone = (Dog) d.makeCopy();

但是如果不执行所有这些步骤,我们就不能简单地这样做吗?

Dog d = new Dog();
Dog clone = d;

我能想到的唯一用法是通过 Prototype 动态创建克隆对象,因为我们可以传递 Dog 类型超类的任何子类。

我说的对吗?或者还有什么需要补充的吗?

【问题讨论】:

标签: oop design-patterns


【解决方案1】:

这段代码:

Dog d = new Dog();
Dog clone = d;

不创建对象的副本。您将拥有从变量dclone 链接的相同对象。您可以通过向 Dog 类添加一些字段并在克隆中分配它的值来检查这一点。之后检查 d 的值。应该是一样的。

makeCopy 的正确实现应该调用 new 运算符,它会创建一个全新的对象并用原型的数据填充它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-23
    • 2019-03-10
    • 1970-01-01
    • 1970-01-01
    • 2020-01-14
    相关资源
    最近更新 更多