Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How could the command pattern be replaced by lambda expressions?

This is kind of a follow-up to another question (Reuse code for looping through multidimensional-array) where my specific problem was resolved by using the command-pattern. My problem was, that I had multiple methods performing operations on every element of a two-dimensional array - and therefore a lot of duplicate code. Instead of having many methods like so...

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

... I solved it like this:

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

Now if we had lambda expressions in Java, how could this be shortened? How would that look like in general? (Sorry for my poor English)

like image 512
Đinh Carabus Avatar asked Aug 03 '13 20:08

Đinh Carabus


People also ask

What would you use to implement the command pattern?

In a classic implementation, the command pattern requires implementing four components: the Command, the Receiver, the Invoker, and the Client.

Which design pattern can you implement to encapsulate conditional logic in a lambda expression?

The Lambda-enabled Command Pattern.

What is lambda expression in functional programming?

Lambda expressions allow passing a function as an input parameter for another function, which was not possible earlier. In short, lambdas can replace anonymous classes, making the code readable and easy to understand. A lambda expression consists of two parts separated by the “->” operator.

What is a command pattern in Java?

A Command pattern is an object behavioral pattern that allows us to achieve complete decoupling between the sender and the receiver. (A sender is an object that invokes an operation, and a receiver is an object that receives the request to execute a certain operation.


1 Answers

Here simple example with Java 8 lamdas. If you change a bit Command class so it will look like this:

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

Here it will accept value from sub array. Then you could write something like this:

    int[][] array = ... // init array
    Command c = value -> {
         // do some stuff
    };
    Arrays.stream(array).forEach(i -> Arrays.stream(i).forEach(c::execute));
like image 165
aim Avatar answered Sep 18 '22 13:09

aim