避免使用简单的if/else条件可以使用多种方法来达到同样的效果,如下所示:
int num = 2;
String result = "";
switch(num) {
case 1:
result = "One";
break;
case 2:
result = "Two";
break;
case 3:
result = "Three";
break;
default:
result = "Other";
}
System.out.println(result);
Map map = new HashMap<>();
map.put(1, "One");
map.put(2, "Two");
map.put(3, "Three");
int num = 2;
String result = map.getOrDefault(num, "Other");
System.out.println(result);
interface Strategy {
String getResult(int num);
}
class OneStrategy implements Strategy {
@Override
public String getResult(int num) {
return "One";
}
}
class TwoStrategy implements Strategy {
@Override
public String getResult(int num) {
return "Two";
}
}
class ThreeStrategy implements Strategy {
@Override
public String getResult(int num) {
return "Three";
}
}
class Context {
private Strategy strategy;
public Context(Strategy strategy) {
this.strategy = strategy;
}
public String executeStrategy(int num) {
return strategy.getResult(num);
}
}
public class Main {
public static void main(String[] args) {
int num = 2;
Context context = new Context(new TwoStrategy());
String result = context.executeStrategy(num);
System.out.println(result);
}
}
这些方法可以帮助我们更好地组织代码,使其更易读、易维护,并且避免了简单的if/else条件。