serah
serah

Reputation: 2117

Using lambdas in command pattern

I am looking to see how to adapt my existing command pattern implementation to JAVA 8 lambdas.

@FunctionalInterface
public interface Command {

    public void execute(final Vehicle vehicle);
}

public class LeftCommand implements Command {

public void execute(final Vehicle vehicle){
    vehicle.turnLeft();
}

}

public class RightCommand implements Command {

public void execute(final Vehicle vehicle){
    vehicle.turnRight();
}

}

I have a class VehicleManager which calls processValue that looks to create commands based on string L or R that is passed to it as inputValue

processValues(Vehicle vehicle, String inputValue){
if("L".equals(inputValue){
  //create left command here
  Command cmd = (vehicle) -> vehicle.turnLeft(); //ERROR
  Command cmd = () -> vehicle.turnLeft(); //ERROR,expects 1 parameter vehicle to be passed
 }else{
 // create right command here
  Command cmd = (vehicle) -> vehicle.turnRight(); //ERROR
 }
}

I tried creating the command using lambdas as above, but it errors out saying vehicle is already defined.

  1. Can you please advise me as to how I can create left and right command instances here using lambdas?

  2. If I can successfully use lambdas above, then can I do away with my LeftCommand and RightCommand classes?

(I have checked quite a number of links on google, but I could not get this to work).

ADDED THIS POST SOME COMMENTS,

 private void processValues(String line, Vehicle vehicle) {
    List<Command> commands = new ArrayList<>();
    for(char c: line.toCharArray()){
        if(LEFT.equals(c)){
            commands.add(()-> vehicle.turnLeft());
        }else if(RIGHT.equals(c)){
            commands.add(()-> vehicle.turnRight());
        }else if(MOVE.equals(c)){
            commands.add(()-> rover.moveForward());
        }
    }
    commands.forEach((c) -> c.execute());
}

Is this correct?

Upvotes: 0

Views: 1578

Answers (1)

Alex S. Diaz
Alex S. Diaz

Reputation: 2667

The use of lambdas or method references in a Command Pattern will make your RightCommand and LeftCommand classes useless.

In your first example, should be applied to something like this:

private void processValues(Vehicle vehicle, String inputValue) {
  Command command;
  if ("Left".equals(inputValue)) {
    command = v -> v.turnLeft();  // <- With lambda expresion
  } else {
    command = Vehicle::turnRight; // <- With method reference
  }
  command.execute(vehicle);
}

A better explanation can be found in "Using the command pattern with lambda expressions".

Upvotes: 4

Related Questions