正如Luiggi Mendoza 所说,这是a previous question 的后续行动...
如果您使用的是 Java 7,则可以使用switch-case statement for strings
//month is a String
switch (month.toLowerCase()) {
case "january":
monthNumber = 1;
break;
//partsleft out for sake of brevity ..
default:
monthNumber = 0;
break;
}
(摘自上面引用的 Oracle Java 教程。)
重构
但是,这个巨大的 if-else 只是问题的一部分。由于这似乎是随着时间的推移而增长的结构,我建议进行彻底的重构,并使用在我看来是Strategy pattern。你应该:
制定一个涵盖所有用例边界的接口:
interface MyStrategy {
void execute(MyInputContext input, MyOutputContext output);
}
(在 MyInputContext 和 MyOutputContext 中使用 void 方法只是一种方法,这只是一个示例,但要处理有响应的请求,这很有意义,就像 Servlet 的工作方式一样)
将大 IF-ELSE 语句的内容重构为该接口的实例(这些将是策略):
//VERY simplified...
class ReadProfileStrategy implements MyStrategy {
void execute(MyInputContext input, MyOutputContext output) {
//do the stuff that was in the if-else block in the "readProfile" part
}
}
//... at the branching part:
MyInputContext input; //build this here
MyOutputContext output; //build this here
switch (purpose) {
case "readProfile":
// no need to always instantiate this, it should be stateless...
new ReadProfileStrategy().execute();
break;
//... left out for sake of brevity
}
重构步骤 2
如果这样做了,您可以将字符串 ID 添加到接口和实例本身,并完全摆脱 if-else 或 switch 语句,您甚至可以创建一个通过 IOC 容器填充的 Map(如) ,保持最新,并且完全灵活。
class ReadProfileStrategy implements MyStrategy {
String getID() {
return "readProfile";
}
void execute(MyInputContext input, MyOutputContext output) {
//do the stuff that was in the if-else block in the "readProfile" part
}
}
在处理请求时的类中
private final Map<String, MyStrategy> strategyMap; //fill the map using your favorite approach, like using Spring application context, using the getCode() to provide the key of the map
在处理逻辑中:
MyStrategy strategy = strategyMap.get(purpose);
if(strategy!=null) {
strategy.execute();
}
else {
//handle error here
}