mardi 12 juillet 2016

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).

Aucun commentaire:

Enregistrer un commentaire