所以,我一直在阅读设计模式,而原型(prototype)模式让我感到困惑。我相信使用它的要点之一是避免使用 new 运算符。然后我看这个例子:
http://sourcemaking.com/design_patterns/prototype/java/1
首先,他们对 Prototype 的想法实现了一个 clone() 方法,这很奇怪。维基百科还说我需要一个由子类实现的纯虚方法克隆(为什么?)。难道 Java 不是已经提供了这样的方法,可以准确地完成我们需要它做的事情(即创建一个对象的副本而不是从头开始实例化它)吗?其次,clone 方法调用操作符 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";
}
}
如有任何澄清,我们将不胜感激。
最佳答案
原型(prototype)模式的想法是拥有一个蓝图/模板,您可以从中生成您的实例。这不仅仅是为了“避免在 Java 中使用 new”
如果您在 Java 中实现原型(prototype)模式,那么肯定会覆盖 Object 类中现有的 clone()
方法,无需创建新方法。 (还需要实现 Clonable 接口(interface),否则你会得到异常)
举个例子:
// 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 - Java 中的原型(prototype)模式——clone() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17203493/