行为型模式 - 命令模式 (Command Pattern)
命令模式将请求封装成一个对象,从而允许你使用不同的请求、队列或日志来参数化其他对象,同时支持请求的撤销与恢复。以下是几个常见的命令模式经典案例。
// 1. 定义命令接口
interface Command {void execute();void undo();
}// 2. 创建具体命令类
class LightOnCommand implements Command {private Light light;public LightOnCommand(Light light) {this.light = light;}@Overridepublic void execute() {light.on();}@Overridepublic void undo() {light.off();}
}class LightOffCommand implements Command {private Light light;public LightOffCommand(Light light) {this.light = light;}@Overridepublic void execute() {light.off();}@Overridepublic void undo() {light.on();}
}// 3. 创建接收者类
class Light {public void on() {System.out.println("Light is on");}public void off() {System.out.println("Light is off");}
}// 4. 创建调用者类
class RemoteControl {private Command command;public void setCommand(Command command) {this.command = command;}public void pressButton() {command.execute();}public void pressUndo() {command.undo();}
}// 5. 客户端代码
public class CommandPatternDemo {public static void main(String[] args) {// 创建接收者Light light = new Light();// 创建具体命令并绑定接收者Command lightOn = new LightOnCommand(light);Command lightOff = new LightOffCommand(light);// 创建调用者RemoteControl remote = new RemoteControl();// 绑定命令并执行remote.setCommand(lightOn);remote.pressButton(); // 输出: Light is onremote.setCommand(lightOff);remote.pressButton(); // 输出: Light is off// 撤销操作remote.pressUndo(); // 输出: Light is on}
}