代码改变世界

徒手撸设计模式-策略模式

2022-07-12 01:33  hikoukay  阅读(28)  评论(0编辑  收藏  举报

概念

https://www.runoob.com/design-pattern/strategy-pattern.html

策略设计模式一般使用的场景是,多种可互相替代的同类行为,在具体的运行过程中根据不同的情况,
选择其中一种行为来执行,比如支付,有微信支付,支付宝支付,银行卡支付,那么到底使用哪种支付方式,
这是由用户来决定的,再比如购物优惠,用户可以选择使用优惠券,可以选择满减优惠,以及其他优惠方式,
到底是使用优惠券,还是满减,或者其他优惠方式,还是由用户来决定,类似的场景我们都可以考虑使用
策略设计模式,可能对于类似的场景我们最常用的还是ifelse,ifelse的缺点是缺少扩展性,从6大原则来说
不符合开闭原则

场景

 

 

直减:比如在双十一等时间,商家会选择这种方式进行促销,如原价999的商品,直接降价到899。
满减:一般以券的方式发放给用户,当用户消费金额达到一定数目时,直接使用券来抵扣一定额度的现在,
    如图中“满2000减1000”,总价2999,用券后需要2899。
折扣:商家直接打折出售商品,如原价1000元的商品,直接八折出售,实际价格为800元。
N元购:另外一种营销手段,比如1元购1999元的手机,但是并非百分百可购得,而是有一定概率,
    类似于买彩票。

 

写一个对外接口FeeModel

/**
* 策略模式接口
*/
@Service
public interface FeeModel {
    double calculate();
}

 

两个策略实现类

FeeModel_A

/**
 * 策略A
 */
@Service
public class FeeModel_A implements FeeModel {
    @Override
    public double calculate() {
        return 0.1;
    }
}

 

FeeModel_B

/**
 * 策略B
 */
@Service
public class FeeModel_B implements FeeModel {
    @Override
    public double calculate() {
        return 0.2;
    }
}

 

使用策略

@Autowired
private ApplicationContext applicationContext;

@GetMapping("/getFeeModel1")
public ResponseModel getFeeModel1(String feeType)  {
    if (StringUtils.isEmpty(feeType)){
        return new ResponseModel("费率类型不能为空", 500, feeType);
    }
    FeeModel feeModel = applicationContext.getBean(StFlag.FEE_MODEL + feeType, FeeModel.class);
    if (!ObjectUtils.isEmpty(feeModel)){
        double calculate = feeModel.calculate();
        return new ResponseModel("费率计算成功", 200, calculate);
    }
    return null;
}

 

测试案例