大家应该都有过写 if-else 的经历。如果遇到判断条件较多的情况,那代码可能就会很长了,影响了可读性,不方便修改,可维护性也差。如果要进一步优化的话,我们可以采用策略模式来进行重构。虽然策略模式在一定程度上提升了可维护性。但是,也有弊端,那就是需要写更多的类。
除了策略模式以外,还可以采用什么方案能对 if-else 进行优化呢?下面,向大家隆重推荐 Map + Function 的方式。
if-else 方式
首选,先让我们看下最初使用 if-else 是个啥样,如下:
public void testGetName() {
String result = this.getName("on");
log.info("result: {}", result);
}
/**
* if-else 方式实现
*/
public String getName(String code) {
if ("on".equals(code)) {
return "打开";
} else if ("off".equals(code)) {
return "关闭";
} else {
return "未定义";
}
}
Map + Function 方式
下面,我要采用 Map + Function 的方式对上边的代码进行重构。
第一步,创建一个 NameService 类,用来统一处理 if-else 的逻辑,如下:
public class NameService {
private static Map<String, Function<String, String>> mapFunction = new HashMap<>();
/**
* 将各个情况对应的处理逻辑初始化到 mapFunction 中
*/
public NameService() {
mapFunction.put("on", str -> this.getOn(str));
mapFunction.put("off", str -> this.getOff(str));
}
public String getName(String code) {
Function<String, String> fun = mapFunction.get(code);
if (null != fun) {
return fun.apply(null);
}
return "未定义";
}
/**
* 应对 code 为 on 的处理逻辑
* @param str
* @return
*/
private String getOn(String str) {
return "打开";
}
/**
* 应对 code 为 off 的处理逻辑
* @param str
* @return
*/
private String getOff(String str) {
return "关闭";
}
}
这里 getOn(String str)、getOff(String str) 代表不同情况的处理逻辑。getName(String code) 方法是 NameServcie 对外的主要方法。
第二步,再来看看我们要如何使用 NameService 这个类,如下:
public void testGetName() {
NameService ns = new NameService();
String result = ns.getName("off");
log.info("result: {}", result);
}