在业务代码中,是否存在很多分支?需要去写一大堆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 "查询不到开票方式";
}
}