简体   繁体   中英

Objects Oriented Design for Two Classes with the same Fields in Java

I have two classes called ShoppingCart and StoreInventory. These are used in a convenience store system, which involves the business domain of retail.

They both contain a List products field. However, only the ShoppingCart should be able to calculate its own totalCost of all products in the list. Also, these two are suspiciously ENTIRELY different objects but have the same fields (addendum : and METHODS, except ShoppingCart can calculate its total value).

What are the best ways thru interfaces and inheritance can this be solved?

Here is my understanding of the issue, please correct me if I am wrong.

You have an inventory class, and every item which can be sold in the store is kept as an instance of this class. You also have a shopping cart class. Shopping cart contains a list of the products it contains. Shopping cart can also calculate the combined price of all of its items.

If this is true, I have a few suggestions.

  • I would suggest creating another class, "item" to store an individual item in the store. This allows store inventory to be a list of items. Item can have fields for price, and potentially information about stock and vendors.
  • I would suggest a driver class to handle the creation/modification of shopping carts, and the modification of store inventory, however you decide to handle it. It may even make sense to have one driver for the customer (shopping carts) and one for the owner/employees (inventory/items).

If you did want to use inheritance, you could write up an item list class, which would create a list of items, and contain methods for add, remove, modify, etc. Then you could write shopping cart and store inventory as subclasses of this, with each extending item list, but having their own methods as well, for example, the price summation in shopping cart. This becomes a bad idea if you want to have a separate item class for shoppers and employees. For example, the one for shopper includes quantity bought and price, while the one for employees includes quantity in stock and vendor information as well as price. In this case you would need multiple different item classes, and the inheritance would no longer work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM