3 回答

TA貢獻1785條經驗 獲得超4個贊
就像Peter Lawrey在Mureinik's answer的評論部分提到的那樣,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
}

TA貢獻1808條經驗 獲得超4個贊
更改初始化行
private static List<Product> productList;
到
private static List<Product> productList = new LinkedList<>();
添加productList.add(this)
為構造函數的最后一行。
因此,每次調用 Product 構造函數時,它都會將此實例添加到靜態列表中。
添加回答
舉報