02 策略模式

策略模式

1. 抽象类

//优惠方式抽象类
public abstract class CashSuperService {

    /**
     * 收费
     *
     * @param money 原价
     * @return 折后价
     */
    public abstract double acceptCash(double money);
}

2. 实现类

//原价
public class CashNormalService extends CashSuperService {
    
    @Override
    public double acceptCash(double money) {
        return money;
    }
}

//打折
public class CashRebateService extends CashSuperService {

    /**
     * 折扣
     */
    private double moneyRebate = 1d;

    public CashRebateService(double moneyRebate) {
        this.moneyRebate = moneyRebate;
    }

    @Override
    public double acceptCash(double money) {
        return money * moneyRebate;
    }
}

//满减
public class CashReturnService extends CashSuperService {

    /**
     * 条件
     */
    private double moneyCondition = 0.0d;
    /**
     * 返利
     */
    private double moneyReturn = 0.0d;

    public CashReturnService(double moneyCondition, double moneyReturn) {
        this.moneyCondition = moneyCondition;
        this.moneyReturn = moneyReturn;
    }

    @Override
    public double acceptCash(double money) {
        double result = money;
        if (result >= moneyCondition) {
            result = money - Math.floor(money / moneyCondition) * moneyReturn;
        }
        return result;
    }
}

3. Context上下文

public class CashContext {
    private CashSuperService cashSuperService = null;

    public CashContext(String type) {
        switch (type) {
            case "正常":
                cashSuperService = new CashNormalService();
                break;
            case "满减":
                cashSuperService = new CashReturnService(300, 100);
                break;
            case "打折":
                cashSuperService = new CashRebateService(0.8);
                break;
        }
    }

    public double getResult(double money) {
        if (Objects.isNull(cashSuperService)) {
            throw new RuntimeException("没有此优惠条件");
        }
        return cashSuperService.acceptCash(money);
    }
}

4. 运行结果

@Slf4j
public class Client {
    public static void main(String[] args) {
        try {
            CashContext cashContext = new CashContext("满减");
            if (Objects.isNull(cashContext)) {
                log.info("没有此优惠条件");
            }
            double result = cashContext.getResult(621);
            log.info("优惠后结果: {}", result);
        } catch (Exception e) {
            log.error("计算优惠异常, msg:{}", e.getMessage(), e);
        }
    }
}
posted @ 2020-12-02 22:04  芝諾de乌龟  阅读(57)  评论(0编辑  收藏  举报