javadesign-patternsdatabase-designobject-oriented-analysis

OO Design pattern for shopping cart


I am trying to learn oo design pattern and developing shopping cart application where different cart items will have different types. Each type is will have some additional attributes.

Option 1: Is it good to create a separate class with every cart item with their own attributes and common attributes in base class. In this option, I will have to create multiple classes and corresponding table hierarchy in the database.

Option 2: Create single cart item with type attribute which will identify the type of the attribute. Irrelevant attributes for the particular cart item will be null in this case.

I know this is very basic question but I want to know about how people follow best practices.

Thanks in advance.


Solution

  • I would use Strategy for this, for example:

    public interface CartItem{
      String getName();
    
      BigDecimal getPrice();
    }
    

    Only work with this interface in your shopping cart. This way, if you want a new cart item, just let it implement this interface, and it will work :)

    By using an interface, you still have full freedom in how you design your actual cart items (either having 1 class, or multiple classes)