[英]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.