需要实现一个要求,如果使用Switch案例实现了许多情况,将根据许多情况或许多IF/if/else!
确定代码流的要求。要实现的示例代码:
if(flag='1')
Invoke a new route
else If(flag='2')
Invoke route2
.
.
.
.
else if(flag= 30)
Invoke route 30
除了/其他语句或切换案例外,还有更好的编写此类情况的方法吗?
类似于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
来处理其他参数。您甚至可以通过将reflection
合并到runtime
期间施放功能来使其更具动态性。