原文:https://www.baeldung.com/java-replace-if-statements
1.利用工厂模式
/**
* 通过工厂模式来代替if
* */
public class RelIfByFactory {
public static void main(String[] args) {
System.out.println(calculate(3,6));
}
private static int calculate(int a, int b) {
// TODO Auto-generated method stub
Operation operation = OperatorFactory.getOperation("add")
.orElseThrow(()->new RuntimeException("参数非法"));
return operation.apply(a, b);
}
}
interface Operation{
int apply(int a,int b);
}
class Addition implements Operation{
@Override
public int apply(int a, int b) {
// TODO Auto-generated method stub
return a+b;
}
}
class OperatorFactory{
static Map operMap = new HashMap();
static {
operMap.put("add", new Addition());
}
static Optional getOperation(String operator){
return Optional.ofNullable(operMap.get(operator));
}
}