最近在写业务代码时,发现有一段业务的逻辑非常蛋疼,由于选择逻辑太多,所以需要靠多个 if...else...来实现。优化前大致是这样的:
@Override
public CustomerEntry4App customerHandel(String customerCode, String customerStatus){
if (CustStatusEnum.POTENTIAL.getCode().equals(customerStatus)){
// TODO do something
} else if (CustStatusEnum.NORMAL.getCode().equals(customerStatus)){
// TODO do something
} else if (CustStatusEnum.NON_EFFECTIVE.getCode().equals(customerStatus)){
// TODO do something
}
return null;
}
优化后代码:
@Override
public CustomerEntry4App customerHandel(String custCode, String custStatusId) throws Exception{
InnerCommand innerCommand = context.getInstance(custStatusId);
return innerCommand.queryCustDetailByCustCode(custCode, custStatusId);
}
整体思路-使用策略模式:
- 不通策略均实现 InnerCommand 接口,并注册到 Spring 容器中。
/**
* 正式客户查询
* @param custCode
* @param custStatusId
* @return
* @throws Exception
*/
@Service
public class NormalCommand implements InnerCommand {
@Override
public CustomerEntry4App queryCustDetailByCustCode(String custCode, String custStatusId) throws Exception {
CustomerEntry4App result = new CustomerEntry4App();
// do something
return result;
}
}
/**
* 散客户查询
* @param custCode
* @param custStatusId
* @return
* @throws Exception
*/
@Service
public class PotentialCommand implements InnerCommand {
@Override
public CustomerEntry4App queryCustDetailByCustCode(String custCode, String custStatusId) throws Exception {
CustomerEntry4App result = new CustomerEntry4App();
// do something
return result;
}
}
@Component
public class InnerCommandContext {
private final static Logger LOGGER = LoggerFactory.getLogger(InnerCommandContext.class);
/**
* 获取执行器实例
* @param custStatusId 执行器实例
* @return
*/
public InnerCommand getInstance(String custStatusId) {
Map<String, String> allClazz = CustStatusCommandEnum.getAllClazz();
String clazz = allClazz.get(custStatusId);
InnerCommand innerCommand = null;
try {
innerCommand = (InnerCommand) SpringApplicationContext.getInstance().getBean(Class.forName(clazz));
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
return innerCommand;
}
}
@Override
public CustomerEntry4App queryCustDetailByCustCode(String custCode, String custStatusId) throws Exception {
InnerCommand innerCommand = context.getInstance(custStatusId);
return innerCommand.queryCustDetailByCustCode(custCode, custStatusId);
}
总结
- 当然优化方式有很多,能满足只需要两行代码就能替换以前复杂的 if else,同时也能灵活扩展。
参考
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于