訂單的優(yōu)惠券可以疊加使用碑幅,應(yīng)該如何做呢
責(zé)任鏈模式
一個(gè)功能處理的結(jié)果,需要傳遞給下一個(gè)功能對象
一個(gè)優(yōu)惠券處理完成后,將結(jié)果傳遞給下一個(gè)優(yōu)惠券處理陌僵,形成一個(gè)鏈表
public interface Discount {
public int calculate(int money);
}
/**
* 責(zé)任鏈父類
*/
public abstract class MultyDiscount implements Discount{
protected MultyDiscount nextMultyDiscount;
public MultyDiscount(MultyDiscount nextMultyDiscount){
this.nextMultyDiscount = nextMultyDiscount;
}
public int calculate(int money){
if (this.nextMultyDiscount != null){
return this.nextMultyDiscount.calculate(money);
}
return money;
}
}
/**
* 滿減
*/
public class FullMultyDiscount extends MultyDiscount {
public FullMultyDiscount(MultyDiscount nextMultyDiscount) {
super(nextMultyDiscount);
}
@Override
public int calculate(int money) {
if (money > 200){
System.out.println("優(yōu)惠滿減20元");
money = money - 20;
}
return super.calculate(money);
}
}
/**
* 第二單9折優(yōu)惠
*/
public class SecondMultyDiscount extends MultyDiscount {
public SecondMultyDiscount(MultyDiscount nextMultyDiscount) {
super(nextMultyDiscount);
}
@Override
public int calculate(int money) {
System.out.println("第二單打9折");
Double balance = money * 0.9;
return super.calculate(balance.intValue());
}
}
責(zé)任鏈父類持有下一個(gè)MultyDiscount,只要next不為空铲掐,就傳遞結(jié)果執(zhí)行
private Discount discount;
private List<Fruit> products = new ArrayList<>();
public ShoppingCart(List<Fruit> products){
this.products = products;
}
public void setDiscount(Discount discount) {
this.discount = discount;
}
//提交訂單主流程
public void submitOrder(){
//優(yōu)惠減免
money = discount.calculate(money);
System.out.println("優(yōu)惠減免后:"+ money+"元拾弃,");
}
總結(jié)
- 適用于多個(gè)對象處理同一個(gè)結(jié)果的場景
- 與策略模式一樣,內(nèi)部持有一個(gè)對象摆霉,策略模式是注入不同的對象豪椿,產(chǎn)生不同的結(jié)果,而責(zé)任鏈模式携栋,是多個(gè)對象遍歷處理同一個(gè)請求