这段代码没有以任何方式遵循或违反原型模式吗?

Does this code not follow or violate prototype pattern in any way?

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

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
}

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

所以我们主要用 someExistingObject.clone().

替换创建 (new())

所以不管你是不是改变属性before/after克隆,你都达到了最终目的。所以结果是一样的。

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