0

I got a bit confused designing the classes for a shopping cart application.

A ShoppingCart has a set of ShopCartItems, each of which contains an instance of a Product and the quantity. The ShoppingCart instance is always stored in the session.

As shown below, Invoice has a reference to the Customer, a set of ShopCartItems, date, invoice number, and total amount. How should I design the Order class? I'm thinking it should also contain the Customer, ShopCartItems, and date.

I'm worried about creating redundant classes, but I want the functionality of letting a user cancel an order, so that requires storing them in the DB.

public class Invoice {
    private Long invoiceId;
    private Customer customer;
    private Set<ShopCartItem> shopCartItems;
    private Date invoiceDate;
    private int invoiceNum;
    private float totalAmount;
    private boolean isProcessed;
...
}

class Product{
    private String name;
    private double price;
    ...
}

class ShopCartItem{
    private Product product;
    private int quantity;
    ...
}
4

2 回答 2

1

首先,确切的答案取决于发票和订单类别之间的关系类型。但让我假设 1 个订单将始终只生成 1 个发票。另一方面,一张发票可以与许多订单相关联。

假设您可以在 Order 和 Invoice 类中包含所有客户数据、shopcartItem 等,但为了避免类似数据的多个实例,您需要执行以下操作:

  1. 订单应包含对关联发票的引用。然后你可以在 Order 类中有一个方法: order.isInvoiceGenerated()

  2. Order.addItem(ShopCartItem item) 应该将项目添加到 Order 类和 Order 的关联 Invoice 对象中。

  3. 对于像 Customer/ShopcartItem 对象这样的 Invoice 类,不应该有直接的修改器。所以 invoice.addItem(ShopCart item) 不应该被允许。

  4. 高于 2 点和 3 点将确保 Order 和 Invoice 对象都引用内存中相同的 Customer/ShopCartItem 实例。因此,它将使它们保持一致。

  5. 上述设计确保如果您的客户订单发生变化,需要重新生成发票。如果客户取消订单,发票也必须取消。

请让我知道您对此的看法。

于 2011-07-19T05:42:53.940 回答
1

我在 OO 设计方面没有大量经验,但这是我的两分钱:

我会将 shopCartItems 移到Order并在那里放置Customer参考和Invoice参考。Invoice可以有一个Set<Order>或一个引用并保留它当前拥有的其他成员(除了 shopCartItems)。

于 2011-07-18T04:19:06.197 回答