@Resource
AbcServiceImpl abcServiceImpl;
private Map<Integer,Function<Long,Integer>> actionMappings = new HashMap();
@PostConstruct
public void init(){
//这里type应加枚举,此处举例没有用 1 2 3
actionMappings.put(1,abcServiceImpl :: getASkuStock);
actionMappings.put(2,abcServiceImpl :: getBSkuStock);
actionMappings.put(3,abcServiceImpl :: getCSkuStock);
}
private Integer getASkuStock(Long skuId){
return 1;
}
private Integer getBSkuStock(Long skuId){
return 2;
}
private Integer getCSkuStock(Long skuId){
return 3;
}
@Override
public Object test(Integer type,Long skuId){
if (type.equals(1)){
return getASkuStock(skuId);
} else if (type.equals(2)){
return getBStock(skuId);
} else {
return getCWareSkuStock(skuId);
}
}
@Override
public Object test2(Integer type,Long skuId){
Function<Long,Integer> function = actionMappings.get(type);
if (function == null){
log.error("查询失败");
return 0;
}
return function.apply(skuId);
}
设计模式解决多层if else代码冗余问题 - 直接上代码对比
于 2022-01-21 09:24:50 首次发布