[英]Replacing If Statements?
我試圖使我的代碼更有效,並替換我寫的一堆if語句。 到目前為止,我的程序基本上檢查輸入了什么運算符(例如+, - 等),然后計算它。 例如,1 + 5給出6.當程序評估數字之間的符號(在我的例子中為“+”)時,它將檢查操作符是什么,然后相應地繼續。 例如,如果它是“+”,它將采用1並添加5.代碼的工作方式如下:
switch (op) {
case "+": // Addition
return args[0] + args[1];
case "-": // Subtraction
return args[0] - args[1];
case "*": // Multiplication
return args[0] * args[1];
case "/": // Division
return args[0] / args[1];
我想知道是否有可能用某種語句替換整個塊,該語句將從String中檢測運算符並將其轉換為操作? 我意識到對於一些運算符來說,使用switch語句可能更容易,但是我有很多它們,並且在switch語句頂部和底部評估運算符之間存在5-10ms的差異。
在Java 8中,您可以使用lambda函數的映射:
Map<String, IntBinaryOperator> operators = new HashMap<>();
operators.put("+", (a, b) -> a + b);
operators.put("-", (a, b) -> a - b);
operators.put("*", (a, b) -> a * b);
operators.put("/", (a, b) -> a / b);
...
return operators.get(op).apply(args[0], args[1]);
這里有更多的間接,但它會給你O(1)攤銷查詢時間。
答案是策略模式 - 你已經擁有了很好的Java 8示例,所以這里是pre-lambda版本(這也說明了為什么需要lambdas):
public class CodeTest {
private static interface ArithmeticStrategy {
public double apply(double arg1, double arg2);
}
private static class AddArithmeticStrategy implements ArithmeticStrategy {
@Override
public double apply(double arg1, double arg2) {
return arg1 + arg2;
}
}
// ... other operations
private static Map<String, ArithmeticStrategy> OPS = new HashMap<>();
static {
OPS.put("+", new AddArithmeticStrategy());
}
public static void main(String[] args) {
// Add two numbers and print the result
System.out.println(
OPS.get("+").apply(22.3, 35.4));
}
}
如果你不使用java 8,你可以做類似的事情
public interface Op{
int execute(int[] values);
}
public class Add implements Op{
public int execute(int[] values){
return values[0] + values[1];
}
}
然后你需要的就是定義你的操作圖並填充它
private final Map<String, Op> operations = new HashMap<>();
operations.put("+", new Add());
然后你可以通過調用operations.get(op).execute(args)
來使用它
此結構將允許您使用一個兩個甚至100個參數來支持操作
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.