I want to create a shopping cart project with discounts for products. For instance, if you buy 2 books, you can get 10% off Parker pens. I created a shopping cart example, but without exception handling in this version.
Are my classes Product
, Basket
, Offers
and Discounts
properly structured, or what changes do I need to make to make it right? To calculate discounts, should I iterate my basket or iterate the list of offers? The offers are a little tricky as mentioned at the top.
Product
public class Product {
private String name;
private int price;
...with get methods + hashcode and equals.
Basket
public class Basket {
Map<Product, Integer> items;
public Basket() {
items = new HashMap<>();
}
public Map<Product, Integer> getItems() {
return items;
}
public void addProduct(Product product){
if(items.containsKey(product)){
items.compute(product, (p,q ) -> Integer.valueOf(q+1));
}else{
items.put(product, 1);
}
}
public void removeProduct(Product product){
if(items.get(product).intValue() > 1){
items.compute(product, (p, q) -> Integer.valueOf(q-1));
}else{
items.remove(product);
}
}
}
Discount
public class Discount {
private Product product;
private int discountPercent ;
public Product getProduct() {
return product;
}
public int getDiscountPercent() {
return discountPercent;
}
public Discount(Product product, int discountPercent) {
super();
this.product = product;
this.discountPercent = discountPercent;
}
@Override
public String toString() {
return "Discount [product=" + product + ", discountPercent=" + discountPercent + "]";
}
}
Offer
public class Offer {
private Product product;
private int quantity;
private Discount discount;
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public Discount getDiscount() {
return discount;
}
public void setDiscount(Discount discount) {
this.discount = discount;
}
public Offer(Product product, int quantity, Discount discount) {
super();
this.product = product;
this.quantity = quantity;
this.discount = discount;
}
@Override
public String toString() {
return "Offer [product=" + product + ", quantity=" + quantity + ", discount=" + discount + "]";
}
}