Как Питер Лори упомянул об этом в разделе комментариев Ответ Мурейника , имея коллекцию static
в POJO - не лучшее решение.
Я бы предложил использовать простой фасад. Это ограничивает существование списка жизнью фасада и не включает логику коллекции в POJO.
public class FacadeProduct {
private List<Product> cacheProduct = new ArrayList<>();
public Product createProduct(float defaultPrice, Currency defaultCurrency, String name){
Product p = new Product(defaultPrice, defaultCurrency, name);
cacheProduct.add(p);
return p;
}
}
Это было бы довольно просто для использования.
public static void main(String ars[]){
{
FacadeProduct f = new FacadeProduct();
{
Product p1 = f.createProduct(1f, null, "test1");
Product p2 = f.createProduct(1f, null, "test2");
Product p3 = f.createProduct(1f, null, "test3");
// Here, the list have 3 instances in it
}
// We lose the p1, p2, p3 reference, but the list is still holding them with f.
}
//Here, we lose the f reference, the instances are all susceptible to be collected by the GC. Cleaning the memory
}