I am working on a shopping cart application which will output price of cart. I have 3 classes for this Cart, Purchase, Product
public class Product {
private int id;
private String name;
private double price;
Offer offer;
// getter setter
public double getPrice(int quantity) {
return offer.getPrice....
}
}
public class Purchase {
Product product;
int quantity;
// getter setter
public double getPrice() {
return product.getPrice(quantity);
}
}
public class Cart {
List<Purchase> purchase = new ArrayList<Purchase>();
Offer offer;
Integer loyalityPoints;
//getter setter
public double getTotal(){
double total = 0;
for (Purchase purchase : purchase) {
total += purchase.getPrice();
}
double finalPrice = offer.getPrice(total,....;
return finalPrice;
}
}
As shown above individual product can have offer and cart can also have offer.
Initially I thought of having offer factory. OfferPrice can be abstract class & its child could be buyonegetoneprice, buytwogetoneprice, 50precentoffprice but then input for buyonegetoneprice will be qunatity and price and input for 50precentoffprice is only price.
This means 2 different method but implementor of OfferPrice is concerned with only one implementation.
Also how could offer on cart look like? offer on cart can be based on customer loyalityPoints or 50percentoff or something else.
How to design these offers for cart and individual product in a way that could be extensible?
From your example you may need different Offer strategy. In my opinion the You should have all these three classes loosely coupled by using interfaces. Create OfferStrategy and subclasses like Product based offer, Price based offer etc.
This also looks like something that can benefit from Rules engine (You can dynamically change Offer for entire application without stopping the application)
Here is my suggestion for the design (Interfaces for each class, strategy to encapsulate different Offer algorithms which internally use Rules): *Ixxx represents interface, <- represents is a relation
IOffer <- Offer , IProduct <- Product , IPurchase <- Purchase , IOfferStragegy <- OfferStrategy* (Different implementations with common interface method) ICart <- Cart Cart has products and offers.
Here are the benefits/reason for doing this :
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With