Добавление объектов в список - PullRequest
0 голосов
/ 07 сентября 2018

Это может быть очень простое решение, но я только начал изучать 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;
    }
}

Ответы [ 4 ]

0 голосов
/ 07 сентября 2018

Инициализируйте productList со значением null, а затем измените конструктор следующим образом:

public Product(float defaultPrice, Currency defaultCurrency, String name) {
        this.id = IdGenerator.createID();
        this.defaultPrice = defaultPrice;
        this.defaultCurrency = defaultCurrency;
        this.name = name;
        if (productList == null) productList = new ArrayList<>();
        productList.add(this);
    }
0 голосов
/ 07 сентября 2018

Вы можете просто добавить недавно созданный Product в список в его конструкторе:

public class Product {

    private int id;
    private String name;
    private float defaultPrice;
    private Currency defaultCurrency;
    private Supplier supplier;
    private static List<Product> productList = new LinkedList<>();
    private ProductCategory productCategory;

    public Product(float defaultPrice, Currency defaultCurrency, String name){
        this.id = IdGenerator.createID();
        this.defaultPrice = defaultPrice;
        this.defaultCurrency = defaultCurrency;
        this.name = name;
        productList.add(this);
    }
}
0 голосов
/ 07 сентября 2018

Как Питер Лори упомянул об этом в разделе комментариев Ответ Мурейника , имея коллекцию 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
}
0 голосов
/ 07 сентября 2018

Изменить строку инициализации

private static List<Product> productList;

до

private static List<Product> productList = new LinkedList<>();

Добавьте productList.add(this) в качестве последней строки конструктора.

Таким образом, каждый раз, когда вы вызываете конструктор Product, он добавляет этот экземпляр в статический список.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...