命令模式是一种行为型设计模式,它将请求封装成一个对象,从而使您可以使用不同的请求、队列或日志来参数化其他对象。命令模式还支持可撤销操作。
下面是一个简单的Java实现命令模式的示例:
首先,我们定义一个命令接口,它包含一个执行方法和一个撤销方法:
public interface Command { void execute(); void undo(); }
然后,我们实现具体的命令类,这里我们以一个简单的电灯开关为例:
public class LightOnCommand implements Command { private Light light; public LightOnCommand(Light light) { this.light = light; } public void execute() { light.turnOn(); } public void undo() { light.turnOff(); } } public class LightOffCommand implements Command { private Light light; public LightOffCommand(Light light) { this.light = light; } public void execute() { light.turnOff(); } public void undo() { light.turnOn(); } }
接下来,我们定义一个遥控器类,它包含一组命令对象:
public class RemoteControl { private Command[] onCommands; private Command[] offCommands; private Command undoCommand; public RemoteControl() { onCommands = new Command[7]; offCommands = new Command[7]; Command noCommand = new NoCommand(); for (int i = 0; i < 7; i++) { onCommands[i] = noCommand; offCommands[i] = noCommand; } undoCommand = noCommand; } public void setCommand(int slot, Command onCommand, Command offCommand) { onCommands[slot] = onCommand; offCommands[slot] = offCommand; } public void onButtonPressed(int slot) { onCommands[slot].execute(); undoCommand = onCommands[slot]; } public void offButtonPressed(int slot) { offCommands[slot].execute(); undoCommand = offCommands[slot]; } public void undoButtonPressed() { undoCommand.undo(); } }
最后,我们可以使用这些类来控制电灯的开关:
public class Client { public static void main(String[] args) { RemoteControl remoteControl = new RemoteControl(); Light livingRoomLight = new Light(); LightOnCommand livingRoomLightOn = new LightOnCommand(livingRoomLight); LightOffCommand livingRoomLightOff = new LightOffCommand(livingRoomLight); remoteControl.setCommand(0, livingRoomLightOn, livingRoomLightOff); remoteControl.onButtonPressed(0); // turn on the living room light remoteControl.offButtonPressed(0); // turn off the living room light remoteControl.undoButtonPressed(); // undo the last command (turn off the living room light) } }
这个例子中,我们使用命令模式将电灯的开关操作封装成了命令对象,并将这些命令对象存储在遥控器中。当用户按下遥控器上的按钮时,遥控器会调用相应的命令对象的执行方法。如果用户想要撤销上一次操作,遥控器会调用相应的命令对象的撤销方法。