我想在这里使用装饰模式。 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