这是聚合的正确用法吗
is this the correct use of aggregation
我想模拟一个收银系统。交易结束时,收据会显示在显示器上。我创建了一个名为 Receipt 的 class,它包含有关客户购买的商品的信息、小计和客户姓名。因此,在收据 class 中,我创建了一个产品 ArrayList 和一个买家对象作为实例变量。 toString() 函数将 return 一个漂亮的格式化字符串。
我不确定是否应该使用 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;
}
}
一切看起来都很好,你几乎做对了。
constrctor 中的一个小修正是你不需要再有一个新的数组列表。
就
this.purchased_products = purchased_products;
够了。
我想模拟一个收银系统。交易结束时,收据会显示在显示器上。我创建了一个名为 Receipt 的 class,它包含有关客户购买的商品的信息、小计和客户姓名。因此,在收据 class 中,我创建了一个产品 ArrayList 和一个买家对象作为实例变量。 toString() 函数将 return 一个漂亮的格式化字符串。
我不确定是否应该使用 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;
}
}
一切看起来都很好,你几乎做对了。
constrctor 中的一个小修正是你不需要再有一个新的数组列表。
就
this.purchased_products = purchased_products;
够了。