Java中的Prototype Pattern - clone()方法

Lea*_*uto 11 java design-patterns clone cloneable prototype-pattern

所以,我一直在阅读设计模式,原型模式让我困惑.我相信使用它的一个要点是避免使用new运算符.然后我看看这个例子:

http://sourcemaking.com/design_patterns/prototype/java/1

首先,他们对Prototype的想法实现了一个clone()方法,这很奇怪.维基百科还说我需要一个纯子方法克隆来实现子类(为什么?).Java是否已经提供了这样的方法,正是我们需要它做的事情(这是创建一个对象的副本而不是从头开始实例化)?其次,clone方法调用new new!当然这个例子是错的?(在这种情况下,我应该在其他地方学习设计模式,嘿?).有人能说出这种纠正是否正确吗?:

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";
    }
  } 
Run Code Online (Sandbox Code Playgroud)

任何澄清表示赞赏.

ger*_*tan 10

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

如果您在Java中实现原型模式,则无论如何都是覆盖clone()Object类中的现有方法,无需创建新方法.(还需要实现Clonable接口或者你会得到异常)

举个例子:

// 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");
Run Code Online (Sandbox Code Playgroud)