繁体   English   中英

如果更改陈述?

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM