【问题标题】:Does this code not follow or violate prototype pattern in any way?此代码是否不以任何方式遵循或违反原型模式?
【发布时间】:2016-09-24 04:48:34
【问题描述】:

我没有获取克隆对象并修改属性,而是首先修改了对象的属性,然后返回了它的克隆。在规则方面和性能方面有什么区别吗?此外,有关设计的任何其他建议都会很棒。谢谢。

public class Category implements Cloneable {

  private int id;
  private String title;
  private int totalGames;

  // getters and setters
  public Category clone() {
    try {
      return (Category)super.clone();
    } catch(CloneNotSupportedException ex) {
      return null;
    }
  }
}


public class CategoryCache {

  private static Category category = new Category(0, null, 0);

  private CategoryCache() {

  }

  public static Category getCategory(int id, String title, int totalGames) {
    category.setId(id);
    category.setTitle(title);
    category.setTotalGames(totalGames);
    return category;
  }
}


while (<100 times>) {            
  Category category = CategoryCache.getCategory(<var1>, <var2>, <var3>).clone();
  arlCategory.add(category); // add to arraylist
}

【问题讨论】:

标签: java design-patterns prototype-pattern


【解决方案1】:

事实上,Prototype 不仅仅是一种模式,它还是一种用于提高 Java 性能的变通方法。我们需要了解的基本内容是“只要我们认为直接创建看起来成本高昂,我们就需要原型,因此我们使用的是现有原型的克隆而不是新创建。

所以我们首先将创建 (new()) 替换为 someExistingObject.clone()

所以无论你是在克隆之前/之后更改属性都没有关系,你已经达到了最终目标。所以结果是一样的。

您的方式唯一不同的是,您用于克隆目的的对象(您一次又一次地使用)很可能是专用于克隆过程的对象,不能执行任何其他工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-13
    • 1970-01-01
    • 2020-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-29
    • 2015-03-22
    相关资源
    最近更新 更多