【发布时间】:2015-05-30 09:20:43
【问题描述】:
我在理解如何让对象相互了解方面遇到了问题。
在我的简单示例中,我有类:Bill、Customer、Checkout 和 Cart。客户有他们的bills 列表,购物车关联到customer 并结帐完成购买操作(将bill 添加到customer)
SO 在方法 public void checkouts(Cart cart) 我初始化新账单 Bill bill = new Bill(cart) 然后我想向客户添加账单。我有 3 种可能的方法:
cart.getCustomer().getBills().add(bill);
// ^^^ directly add bill to ArrayList in Customer
cart.getCustomer().addBill(bill);
// ^^^ Customer get bill and put it itself in their own method
cart.addBillToCustomer(bill);
// ^^^ In this example class Checkout doesn't now anything about customer.
// Responsibility goes to cart which calls getCustomer().addBill(bill)
我猜第一个确实是错误的,因为Checkout 必须知道getBills() 返回array list(这很危险)
在第二个示例中,checkouts 获取与它没有直接关联的客户,并且它必须知道客户界面才能添加账单。
在第三个结帐示例中,与客户没有直接关联,不要使用任何关于客户的知识,它只是将任务委托给cart,cart 直接连接到customer(它有字段客户客户)
哪种解决方案最好,为什么以及为什么其他解决方案更差?
【问题讨论】:
标签: java class oop design-patterns