将对象添加到列表

这可能是一个非常简单的解决方案,但我刚刚开始学习 Java。我想将每个实例化的产品添加到产品列表中。有没有办法在不修改访问修饰符的情况下解决这个问题?


public class Product {

    private int id;

    private String name;

    private float defaultPrice;

    private Currency defaultCurrency;

    private Supplier supplier;

    private static List<Product> productList;

    private ProductCategory productCategory;


    public Product(float defaultPrice, Currency defaultCurrency, String name) {

        this.id = IdGenerator.createID();

        this.defaultPrice = defaultPrice;

        this.defaultCurrency = defaultCurrency;

        this.name = name;

    }

}


素胚勾勒不出你
浏览 122回答 3
3回答

九州编程

就像Peter Lawrey在Mureinik's answer的评论部分提到的那样,static在 POJO 中拥有一个集合并不是最好的解决方案。我建议使用简单的外观。这将列表存在限制为外观生命并且不包括 POJO 中集合的逻辑。public class FacadeProduct {&nbsp; &nbsp; private List<Product> cacheProduct = new ArrayList<>();&nbsp; &nbsp; public Product createProduct(float defaultPrice, Currency defaultCurrency, String name){&nbsp; &nbsp; &nbsp; &nbsp; Product p = new Product(defaultPrice, defaultCurrency, name);&nbsp; &nbsp; &nbsp; &nbsp; cacheProduct.add(p);&nbsp; &nbsp; &nbsp; &nbsp; return p;&nbsp; &nbsp; }}这将非常简单易用。public static void main(String ars[]){&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; FacadeProduct f = new FacadeProduct();&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Product p1 = f.createProduct(1f, null, "test1");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Product p2 = f.createProduct(1f, null, "test2");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Product p3 = f.createProduct(1f, null, "test3");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Here, the list have 3 instances in it&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; // We lose the p1, p2, p3 reference, but the list is still holding them with f.&nbsp; &nbsp; }&nbsp; &nbsp; //Here, we lose the f reference, the instances are all susceptible to be collected by the GC. Cleaning the memory}

炎炎设计

更改初始化行private static List<Product> productList;到private static List<Product> productList = new LinkedList<>();添加productList.add(this)为构造函数的最后一行。因此,每次调用 Product 构造函数时,它都会将此实例添加到静态列表中。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java