[英]How to implement numerous conditions in java other than switch case and if/else?
如果使用switch case或很多if / else来实现,则需要实现一个根据很多情况决定代码流的要求!
要实现的示例代码:
if(flag='1')
Invoke a new route
else If(flag='2')
Invoke route2
.
.
.
.
else if(flag= 30)
Invoke route 30
除了if / else语句或切换用例之外,是否有更好的方法来编写此类用例?
类似于jBPM
之类的工作流引擎的内部实现,但是我实际上不能包括工作流引擎,因为它使应用程序变得沉重!
任何建议表示赞赏!
这就是我上面所说的。
import java.util.function.*;
public class MethodCalls {
public static void main(String[] args) {
new MethodCalls().start();
}
public void start() {
Map<Integer, Function<Integer, Integer>> callTable = new HashMap<>();
callTable.put(1, a -> prod(a));
callTable.put(2, a -> sub(a));
Random r = new Random();
r.ints(10, 1, 3).forEach(b -> System.out.println("The answer is "
+ callTable.get(b).apply(r.nextInt(20) + 20) + "\n"));
}
public int prod(int v) {
System.out.println("Multiplying " + v + " by " + 40);
return v * 40;
}
public int sub(int v) {
System.out.println("Subtracting " + 30 + " from " + v);
return v - 30;
}
}
这只是一个玩具,但是它演示了使用调用表来增强switch
和/或if/else
语句的可能性。 您可能需要几个maps
来处理不同的interface
类型,甚至可能声明自己的functional interfaces
来处理其他参数。 您甚至可以通过在runtime
将reflection
合并到强制转换函数中来使其更加动态。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.