MapFunction -> 更完美的解决“if-else”

        在业务代码中,是否存在很多分支?需要去写一大堆if-else 或者 switch 去控制代码去走哪个分支,完成那段业务代码。如:

if (resourceType.equals("现金支付")){
    //payService.cash();
    return "现金支付代码返回结果"
} else if (resourceType.equals("微信支付")){
    //payService.wx();
    return "微信支付代码返回结果"
}else if (resourceType.equals("支付宝")){
    //payService.zfb();
    return "支付宝支付代码返回结果"
}else ...

        除了上面的if-else 或者 switch 还有什么办法呢?是不是有很多小伙伴会想到策略模式去代替。但其实策略模式跟多的是解决代码扩展,更易读,更容易维护。

Map + lambda表达式完美代替这个
  •         判断条件放在key上
  •         对应的业务实现代码放在value上

这就是本次的解决大体思想,这样写更易读,也方便拓展。后端人员能直观的看出代码分支流向。

代码实现:
//业务逻辑分支,实现代码
@Service
public class InvoiceTypeService {

    public String kingdee(String userId){
        return userId+"金蝶开票";
    }

    public String flyCloud(String userId){
        return userId+"云飞票开票";
    }

    public String pxm(String userId){
        return userId+"票小米开票";
    }
}

判断分支类

@Service
public class MapFunction {

    private Map<String, Function<String,String>> map = new HashMap<>();

    @Autowired
    private InvoiceTypeService invoiceTypeService;

    //模拟入参(用户唯一ID)
    private String userId = "Gz001";

    /**
     * 该注解作用:依赖注入完成后执行初始化操作
     *  将我们的业务提前放入我们MapFunction中
     */
    @PostConstruct
    public void init(){
        map.put("kingdee",userId -> invoiceTypeService.kingdee(userId));
        map.put("flyCloud",userId -> invoiceTypeService.flyCloud(userId));
        map.put("pxm",userId ->invoiceTypeService.pxm(userId));
    }

    public String getResult(String type){
        //通过type取出对应的function
        Function<String, String> result = map.get(type);

        if(result != null){
            //执行对应function并注入我们想注入的参数
            return result.apply(userId);
        }
        return "查询不到开票方式";
    }
}
测试环节

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值