Java – How to design the classes for a simple shopping cart example using Strategy Design Patterns

design-patternsjavaobject-orientedpatterns-and-practicessoftware

First year of Software Engineering, and we're learning OOP within Java. Came across an extension task to gain more credits. But could not think of what to do:

First Step: Design a checkout system

Build a checkout system for a shop which sells 3 products say Bread, Milk, and Bananas.
Costs of the products are : Bread – $1, Milk – $0.60 and Banana – $0.40
Build a system to checkout a shopping cart that can have multiples of these 3 products and displays the order total. Examples are: Bread, Milk, Banana = $2.00 Bread, Bread, Milk, Banana = $3.00 Milk, Banana, Milk, Banana = $2.00

As a next step: enhance the code to apply the below discounts and offers

Buy one bread and get another bread for free Buy 3 Milk for the price of 2 Buy 2 Bananas and get one free

First part was rather straightforward, i went on and completed this by doing:

public class Cart {

    List<String> items;
    double total;

    public Cart(){
        items = new ArrayList<String>();
    }

    public void addItems(String item){
        items.add(item);
    }

    public void removeItems(String item){
        items.remove(item);
    }

    public void getNumberOfItems(){
        System.out.println(items.size());
    }

    public String getItemName(int index){
        return items.get(index);
    }

    public void getTotalOfCart(){
        total = 0;
        for(String x: items){
            if (x.equals("A")){
                total += 3.0;
            }else if (x.equals("B")){
                total += 5.0;
            }else if (x.equals("C")){
                total += 2.50;
            }
        }
        System.out.println(total);
    }
}

But now when it comes to implementing the second part of the challenge. I have no idea where to start and what to do. I'm sure this problem is probably fairly standard in terms of implementing rules for things like discounts etc. I just wanna know what my next step(s) is/should be & where possible to start if i wanted to go further with the theory behind this.

Best Answer

Since you are learnig OOP i help you with the busines part:

You have product specific discounts (discount strategy) that depend on cartitem quantity

Milk $0.60
Buy 3 Milk for the price of 2 = discount is 0.60 per 3 Milk = 0.60*int(cartitem.quantity / 3)

cart has 7 milk รก 0.60 = 4.20
minus milk-discount int(quanty/3) * 0.60 = int(7/3) * 0.60 = 2 * 0.60 = 1.2


4.20
- 1.2
= 3.00

This should give you enough info to design classes Product , ProductDiscountStrategy, Cart, CartItem

Related Topic