pattern-策略模式优化if -else
避开闲谈,直入主题
开发中,常常会遇到大量的 if else
判断,如果 if else
太多了,就会导致代码层级、阅读性变差,在此基础上,我利用了空余时间重构了 if else
代码块
@Override
public Map<String, Object> doGetAnyProcess(ProcessVo model) {
if (StringUtils.isBlank(model.getFlowName())) {
return Collections.EMPTY_MAP;
}
int count = 0;
this.prefixProcess(model);
// flowName用于对不同流程的判断使用
String index = model.getFlowName();
// 创建空集合
List<Map<String, Object>> process = Collections.EMPTY_LIST;
// XX流程
if (IFlowEnum.APPLY_FLOW.get().equals(index)) {
// TODO
}
// XX流程
else if (IFlowEnum.DRAW_FLOW.get().equals(index)) {
// TODO
}
// XX流程
else if (IFlowEnum.STORAGE_FLOW.get().equals(index)) {
// TODO
}
// XX流程
else if (IFlowEnum.ORDER_FLOW.get().equals(index)) {
// TODO
}
// XX流程
else if (IFlowEnum.PLAN_FLOW.get().equals(index)){
// TODO
}
// XX流程
else if (IFlowEnum.SEMI_FLOW.get().equals(index)) {
// TODO
}
// XX流程
else if (IFlowEnum.FINISH_FLOW.get().equals(index)) {
// TODO
}
// XX流程
else if (IFlowEnum.FALL_FLOW.get().equals(index)) {
// TODO
}
// XX流程
else if (IFlowEnum.SEM_FALLBACK_FLOW.get().equals(index)) {
// TODO
}
return this.assemblyData(process, count);
}
从以上的代码可以看出,不但方法的总行数多,而且非常不利于阅读,所以在挣扎之中,使用了设计模式中 策略模式
来对其进行优化了一点
1、创建接口,提供公共方法
//
public interface Strategy {
/**
* 抽取公共方法
* @param vo 封装的参数实体类
* @return
*/
Map<String, Object> process(ProcessVo vo);
}
2、创建 Context
,提供对于条件的逻辑
// 这里避免了创建更多的类文件,我选择在 Context 中新建内部类
@Configuration
public class Context {
/**
* 采购流程
* @author zyred
*/
@Configuration
public class AppStartegy implements Strategy {
@Autowired private Mapper mapper;
@Override
public Map<String, Object> process(ProcessVo model) {
// 数据
List<Map<String, Object>> process = this.mapper.**();
// 总条数
Integer count = this.mapper.**(model);
// 处理一下数据
return Context.assemblyData(process, count);
}
}
............... // 以此类推
}
3、为了减少在Controller
中的逻辑,增加一个工厂类 Factory
@Configuration
public class Factory {
@Autowired private Context.AppStartegy appStartegy;
// 根据条件执行判断执行方法
public Map<String, Object> strategyProcess( ProcessVo m){
Map<String, Object> data = new HashMap<>(1);
switch (m.getFlowName()){
case "A" : data= appStartegy.process(m); breake;
.....
default breake;
}
return data;
}
}
4、Service
@Autowired
private Factory factory;
@Override
public Map<String, Object> doGetAnyProcess(ProcessVo model) {
this.prefixProcess(model);
return factory.strategyProcess(model);
}