我想在這裏使用裝飾模式。 BaseCart是抽象類。購物車擴展了BaseCart並獲得總價。現在我想在不改變現有代碼的情況下給予總購物車價值的折扣。所以我創建了擴展BaseCart的CartDecorator,然後創建TotalDiscountCart,它將獲得總金額,然後對其應用折扣。問題與裝飾設計模式在java
現在我試圖運行下面給出的單元測試沒有給出正確的輸出。產品被添加到購物車中,但是當Cart的getTotalPrice()方法被調用時,則productsWithQuantity爲空。 是否應該添加值?它爲什麼是空的以及如何解決它?
public abstract class BaseCart {
Map<Product, Integer> productsWithQuantity = new HashMap<Product, Integer>();
Double totalPrice = 0.0;
public void addProduct(Product product, Integer quantity){
productsWithQuantity.put(product, quantity);
}
public abstract Double getTotalPrice();
}
public class Cart extends BaseCart{
@Override
public Double getTotalPrice() {
productsWithQuantity.forEach((product ,quantity)-> totalPrice = totalPrice + product.getUnitPrice() * quantity);
return totalPrice;
}
}
public class CartDecorator extends BaseCart{
BaseCart cart;
public CartDecorator(BaseCart cart) {
super();
this.cart = cart;
}
@Override
public Double getTotalPrice() {
return this.cart.getTotalPrice();
}
}
public class TotalDiscountCart extends CartDecorator{
public TotalDiscountCart(BaseCart cart) {
super(cart);
}
@Override
public Double getTotalPrice() {
super.getTotalPrice();
return totalPrice - (percentDiscount(10.0));
}
private Double percentDiscount(Double i) {
return 0.1 * totalPrice;
}
}
@Test
public void shouldGiveDiscountOf9() {
//Given
BaseCart cart = new TotalDiscountCart(new Cart());
Product productDove = new Product("Dove soap", 30.0);
//when
cart.addProduct(productDove, 3);
// then
assertEquals(Double.valueOf(81.0),cart.getTotalPrice());
}
您能否詳細說明一下,「CartDecorator創建購物車界面不會從BaseCart的子類中獲益」。 – user1298426
@ user1298426查看更新。 – lexicore