这是聚合的正确用法

时间:2015-09-22 06:23:02

标签: java oop arraylist object-oriented-analysis

我想模拟收银系统。在交易结束时,收据将显示在监视器上。我创建了一个名为Receipt的类,它包含有关客户购买的商品,小计和客户名称的信息。因此,在Receipt类中,我创建了一个产品的ArrayList和一个买方对象作为实例变量。 toString()函数将返回一个很好的格式化字符串。

我不确定是否应该使用ArrayList作为实例变量,我不知道聚合是否是最佳选择。

import java.util.ArrayList;

public class Receipt {
    private ArrayList<Product> purchased_products;
    private double total_price;
    private double total_with_tax;
    private Buyer buyer;

    public Receipt(Buyer buyer, ArrayList<Product> purchased_products, 
            double total_price, double total_with_tax) {
        this.purchased_products = new ArrayList<>(purchased_products);
        this.total_price = total_price;
        this.buyer = buyer;
        this.total_with_tax = total_with_tax;
    }

    @Override
    public String toString() {
        String content = "Receipt: \nConvenience Store\n";
        content += "Balance Summary:\n";
        for (Product product : purchased_products) {
            content += product + "\n";
        }
        content += String.format("%d Subtotals: $%.2f\nAmount Paid: $%.2f\n", purchased_products.size(), total_price,
                total_with_tax);
        content += buyer.toString() + "\n";
        content += "Thank you for shopping with us. Have a wonderful day!\n";
        return content;
    }

}

1 个答案:

答案 0 :(得分:1)

一切看起来都很好,你差不多正确。

constrctor中的一个小修正是你不需要再次有一个新的数组列表。

只是

 this.purchased_products = purchased_products;

够了。