在Java中的原型模式

在Java中的原型模式

本文介绍了在Java中的原型模式 - clone()方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我一直在阅读设计模式,原型模式让我感到困惑。我相信使用它的一点是避免使用新的操作符。然后我看这个例子:

So, I've been reading on Design Patterns and the Prototype Patterns confuses me. I believe one of the points of using it is avoiding the need for using the new operator. Then I look at this example:

首先,他们对Prototype的想法实现了一个clone()方法,这是奇怪的。维基百科还表示,我需要一个纯虚拟方法克隆来实现子类(为什么?)。 Java是不是已经提供了这样一种方法,正是我们需要做的(这是创建对象的副本而不是从头开始)。其次,克隆方法调用运算符新的!当然这个例子是错的吗? (在这种情况下,我应该在其他地方学习设计模式吗?)有人可以告诉这个修正是否正确?:

First, Their idea of Prototype implements a clone() method, which is weird. Wikipedia also says I need a pure virtual method clone to be implemented by subclasses (why?). Doesn't Java already provide such a method, doing exactly what we need it to do (which is to create a copy of an object instead of instancing it from scratch)? Second, the clone method invokes the operator new! Surely the example is wrong? (In that case I should be studying Design Patterns elsewhere, heh?). Can someone tell if this correction makes it right?:

static class Tom implements Cloneable implements Xyz {
    public Xyz    cloan()    {
      return Tom.clone(); //instead of new I use clone() from Interface Cloneable
    }
    public String toString() {
      return "ttt";
    }
  }

任何澄清表示赞赏。

推荐答案

原型模式的想法有一个蓝图/模板,您可以从中生成实例。不仅仅是为了避免在Java中使用新的

The idea of prototype pattern is having a blueprint / template from which you can spawn your instance. It's not merely to "avoid using new in Java"

如果在Java中实现原型图,那么所有这些都是覆盖现有的克隆( )方法从Object类,不需要创建一个新的。 (还需要实现可克隆的界面,否则会得到例外)

If you implement prototype pattern in Java, then yes by all means override the existing clone() method from Object class, no need to create a new one. (Also need implement Clonable interface or you'll get exception)

举个例子:

// Student class implements Clonable
Student rookieStudentPrototype = new Student();
rookieStudentPrototype.setStatus("Rookie");
rookieStudentPrototype.setYear(1);

// By using prototype pattern here we don't need to re-set status and
// year, only the name. Status and year already copied by clone
Student tom = rookieStudentPrototype.clone();
tom.setName("Tom");

Student sarah = rookieStudentPrototype.clone();
sarah.setName("Sarah");

这篇关于在Java中的原型模式 - clone()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 20:34