gpt4 book ai didi

java - 在命令模式中使用 lambda

转载 作者:行者123 更新时间:2023-12-01 21:24:50 25 4
gpt4 key购买 nike

我希望了解如何使我现有的命令模式实现适应 JAVA 8 lambda。

@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();
}

}

我有一个类 VehicleManager,它调用 processValue,它会根据作为 inputValue 传递给它的字符串 L 或 R 创建命令

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

我尝试使用上面的 lambda 表达式创建命令,但错误提示车辆已定义。

  1. 您能否告诉我如何使用 lambda 在此处创建左右命令实例?

  2. 如果我可以成功使用上面的 lambda,那么我可以取消 LeftCommand 和 RightCommand 类吗?

(我在谷歌上检查了很多链接,但我无法让它工作)。

添加了此帖子的一些评论,

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

这是正确的吗?

最佳答案

在命令模式中使用 lambda 或方法引用将使您的 RightCommandLeftCommand 类毫无用处。

在你的第一个例子中,应该应用于这样的事情:

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

更好的解释可以在"Using the command pattern with lambda expressions"中找到。 .

关于java - 在命令模式中使用 lambda,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38333386/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com