在Java中,命令模式(Command Pattern)是一种行为设计模式,它允许你将一个请求封装为一个对象,从而使你能够使用不同的请求、队列或日志请求参数化其他对象。此外,它还支持可撤销的操作。
以下是如何在Java中实现命令模式的步骤:
public interface Command {
void execute();
}
public class LightOnCommand implements Command {
Light light;
public LightOnCommand(Light light) {
this.light = light;
}
@Override
public void execute() {
light.on();
}
}
public class LightOffCommand implements Command {
Light light;
public LightOffCommand(Light light) {
this.light = light;
}
@Override
public void execute() {
light.off();
}
}
在这个例子中,我们有两个具体命令:LightOnCommand 和 LightOffCommand,它们分别实现了 Command 接口。这些类接收一个 Light 对象作为参数,并在 execute 方法中调用相应的 on() 或 off() 方法。
public class Light {
public void on() {
System.out.println("Light is ON");
}
public void off() {
System.out.println("Light is OFF");
}
}
在这个例子中,Light 类是接收者,它包含了 on() 和 off() 方法。
public class RemoteControl {
Command command;
public void setCommand(Command command) {
this.command = command;
}
public void pressButton() {
command.execute();
}
}
在这个例子中,RemoteControl 类是调用者,它包含一个 Command 接口类型的成员变量 command。setCommand 方法用于设置要执行的命令,而 pressButton 方法则调用该命令的 execute 方法。
public class Main {
public static void main(String[] args) {
Light light = new Light();
Command lightOn = new LightOnCommand(light);
Command lightOff = new LightOffCommand(light);
RemoteControl remoteControl = new RemoteControl();
remoteControl.setCommand(lightOn);
remoteControl.pressButton(); // 输出 "Light is ON"
remoteControl.setCommand(lightOff);
remoteControl.pressButton(); // 输出 "Light is OFF"
}
}
在这个例子中,我们首先创建了一个 Light 对象和两个具体命令(lightOn 和 lightOff)。然后,我们创建了一个 RemoteControl 对象,并使用 setCommand 方法设置要执行的命令。最后,我们调用 pressButton 方法来执行命令。