【问题标题】:How could the command pattern be replaced by lambda expressions?如何用 lambda 表达式替换命令模式?
【发布时间】:2013-08-04 21:31:24
【问题描述】:

这是对另一个问题 (Reuse code for looping through multidimensional-array) 的跟进,我的具体问题已通过使用命令模式解决。我的问题是,我有多种方法对二维数组的每个元素执行操作 - 因此有很多重复的代码。而不是有很多这样的方法......

void method() {
    for (int i = 0; i < foo.length; i++) {
        for (int j = 0; j < foo[i].length; j++) {
            // perform specific actions on foo[i][j];
        }
    }
}

...我是这样解决的:

interface Command {
    void execute(int i, int j);
}

void forEach(Command c) {
    for (int i = 0; i < foo.length; i++) {
        for (int j = 0; j < foo[i].length; j++) {
            c.execute(i, j);
        }
    }
}

void method() {
    forEach(new Command() {
        public void execute(int i, int j) {
            // perform specific actions on foo[i][j];
        }
    });
}

现在,如果我们在 Java 中有 lambda 表达式,如何缩短它?一般情况下会是什么样子? (对不起我的英语不好)

【问题讨论】:

    标签: java lambda functional-programming java-8


    【解决方案1】:

    这里是 Java 8 lamdas 的简单示例。如果你改变一点Command 类,它会是这样的:

        @FunctionalInterface
        interface Command {
            void execute(int value);
        }
    

    这里它将接受来自子数组的值。然后你可以这样写:

        int[][] array = ... // init array
        Command c = value -> {
             // do some stuff
        };
        Arrays.stream(array).forEach(i -> Arrays.stream(i).forEach(c::execute));
    

    【讨论】:

    • 非常感谢您的回答。你能解释一下“Arrays.stream”方法的作用吗?
    • 它只返回Stream :) 你可以自己try
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-12
    • 2011-12-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-16
    • 1970-01-01
    • 2010-11-25
    相关资源
    最近更新 更多