函数接口替代策列者模式

1、策略者模式

策略者模式 不懂就看
菜鸟教程

应用场景:列入支付方式很多种,优惠卷多种策略,考试组卷策略等等

优惠卷:有商家优惠卷,有平台优惠卷等

在这里插入图片描述

这样不适用策略者模式的话会显得 巴拉巴拉很多影响了可读性 也不方便修改,可维护性低

switch(resourceType){
 case "优惠卷类型1": 
  //优惠的逻辑
  break;
 case "优惠卷类型2": 
   //优惠的逻辑
  break;
 case "优惠卷类型3" :
 //优惠的逻辑
  break;
 case "优惠卷类型4" :
  break;
 ......
 default : logger.info("查找不到该优惠券类型resourceType以及对应的派发方式");
  break;
}

使用策略模式

在这里插入图片描述

switch(resourceType){
  case "优惠卷类型1":
  String grantType=new Context(new RedPaper()).ContextInterface();
  break;
  ..........

2、Map+函数式接口

  @Autowired
  //优惠卷处理路哟及
    private TypeSerive typeSerive;
    private Map<String, Function<String,String>> grantTypeMap=new HashMap<>();
   /**
     *  初始化业务分派逻辑,代替了if-else部分
     *  key: 优惠券类型
     *  value: lambda表达式,最终会获得该优惠券的发放方式
     */
    @PostConstruct
    public void dispatcherInit(){
        grantTypeMap.put("优惠卷类型1",resourceId->typeSerive.type1());
        grantTypeMap.put("优惠卷类型2",resourceId->typeSerive.type2());
    }

 public String getResult(String resourceType){
        //Controller根据 优惠券类型resourceType、编码resourceId 去查询 发放方式grantType
        Function<String,String> result=getGrantTypeMap.get(resourceType);
        if(result!=null){
         //传入resourceId 执行这段表达式获得String型的grantType
            return result.apply();
        }
        return "查询不到该优惠券的发放方式";
    }
@Service
public class TypeSerive {

    public String type1(){
       
        return "type1";
    }
    public String type2(){
        //购物券的发放方式
        return "type2";
    }
}

使用

getResult("优惠卷类型1")
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

张航柯

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值