javadesign-patternsprototype-pattern

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


Instead of getting clone object and modifying attributes, I have first modified attributes of the object and then returned its clone. Is there any difference rule-wise and performance-wise? Also, any other suggestions regarding the design would be great. Thanks.

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
}

Solution

  • Indeed more than a pattern, Prototype is a work around for increasing performance in Java. The basic thing we need to understand is 'we need Prototype whenever we think that direct creation looks costly, hence we are using a clone of an existing one rather than newly creation.

    So primarily we replace the creation (new()) with someExistingObject.clone().

    So it doesn't matter whether you are changing the attributes before/after cloning, you have achieved the ultimate goal. So the results will be same.

    The only difference in your way is, the object you are using for cloning purpose (which you are using again and again) most probably will be a dedicated one only for cloning process, and can not perform any other work.