替换 If 语句?

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]; 

我想知道是否可以用某种语句替换整个块,该语句将从字符串中检测运算符并将其转换为操作?我意识到对于一些运算符来说,使用 switch 语句可能更容易,但我有很多这样的运算符,在 switch 语句顶部和底部评估运算符之间存在 5-10ms 的差异。

在 Java8 中,您可以使用 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) 分摊查找时间。

答案是 Strategy Pattern - 您已经有了很好的 Java 8 示例,所以这里是 pre-lambda 版本(这也说明了为什么迫切需要 lambda):

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)即可使用

这个结构可以让你支持一两个甚至一百个参数的运算