《Head First 设计模式》之命令模式——遥控器
命令模式(Command)
——将“请求”封装成对象,以便使用不同的请求、队列或者日志来参数化其他对象。命令模式也支持可撤销的操作。
- 要点
- 将发出请求的对象和执行请求的对象解耦。
- 被解耦的两者之间通过命令对象进行沟通。命令对象封装了接收者和一个或一组动作。
- 调用者通过调用命令对象的execute()发出请求,使得接收者的动作被调用。
- 通过实现一个undo()方法撤销命令。还可以使用一个堆栈记录操作过程的每一个命令,实现多步撤销。
- 宏命令允许调用多个命令,也支持撤销。
- 命令也可以用来实现日志和事务系统。
1 interface Command { 2 public void execute(); 3 } 4 5 class Light { 6 public void on() { 7 System.out.println("light on"); 8 } 9 10 public void off() { 11 System.out.println("light off"); 12 } 13 } 14 15 class LintOnCommand implements Command { 16 Light light; 17 18 public LintOnCommand(Light light) { 19 this.light = light; 20 } 21 22 @Override 23 public void execute() { 24 light.on(); 25 } 26 27 } 28 29 class SimpleRemoteControl { 30 Command command; 31 32 public SimpleRemoteControl() {} 33 34 public void setCommand(Command command) { 35 this.command = command; 36 } 37 38 public void buttonWasPressed() { 39 command.execute(); 40 } 41 } 42 43 public class Test { 44 public static void main(String[] args) { 45 SimpleRemoteControl control = new SimpleRemoteControl(); 46 Light light = new Light(); 47 LintOnCommand onCommand = new LintOnCommand(light); 48 49 control.setCommand(onCommand); 50 control.buttonWasPressed(); 51 } 52 }