一.定义
命令模式(Command Pattern):将一个请求封装为一个对象,从而使我们可用不同的请求对客户进行参数化;对请求排队或者记录请求日志,以及支持可撤销的操作。命令模式是一种对象行为型模式,其别名为动作(Action)模式或事务(Transaction)模式。
二、模式结构成员构成
• Command: 抽象命令类
• ConcreteCommand: 具体命令类
• Invoker: 调用者
• Receiver: 接收者
• Client:客户类
三.代码示例
1 /** 2 * Command 3 * 抽象命令类 4 */ 5 public interface Command { 6 void execute(); 7 } 8 9 /** 10 * ConcreteCommand 11 * 具体命令类 12 */ 13 public class FlipDownCommand implements Command { 14 private Light theLight; 15 16 public FlipDownCommand(Light light) { 17 this.theLight = light; 18 } 19 20 @Override 21 public void execute() { 22 theLight.turnOff(); 23 } 24 } 25 26 /** 27 * ConcreteCommand 28 * 具体命令类 29 */ 30 public class FlipUpCommand implements Command { 31 private Light theLight; 32 33 public FlipUpCommand(Light light) { 34 this.theLight = light; 35 } 36 37 @Override 38 public void execute() { 39 theLight.turnOn(); 40 } 41 } 42 43 /** 44 * Receiver 45 * 接收者 46 */ 47 public class Light { 48 public Light() { 49 } 50 51 public void turnOn() { 52 System.out.println("The light is on"); 53 } 54 55 public void turnOff() { 56 System.out.println("The light is off"); 57 } 58 } 59 60 /** 61 * Invoker 62 * 调用者 63 */ 64 public class Switch { 65 private List<Command> history = new ArrayList<Command>(); 66 67 public Switch() { 68 } 69 70 public void storeAndExecute(Command cmd) { 71 this.history.add(cmd); // optional 72 cmd.execute(); 73 } 74 } 75 76 /** 77 * Client 78 */ 79 public class Client { 80 81 public static void main(String[] args) { 82 Light lamp = new Light(); 83 Command switchUp = new FlipUpCommand(lamp); 84 Command switchDown = new FlipDownCommand(lamp); 85 86 Switch mySwitch = new Switch(); 87 88 try { 89 if ("ON".equalsIgnoreCase(args[0])) { 90 mySwitch.storeAndExecute(switchUp); 91 } else if ("OFF".equalsIgnoreCase(args[0])) { 92 mySwitch.storeAndExecute(switchDown); 93 } else { 94 System.out.println("Argument \"ON\" or \"OFF\" is required."); 95 } 96 } catch (Exception e) { 97 System.out.println("Arguments required."); 98 } 99 } 100 }
四.优点和缺点分析
优点:
>降低系统的耦合度
>新的命令可以很容易地加入到系统中
>可以方便地实现对请求的Undo和Redo
缺点:
>使用命令模式可能会导致某些系统有过多的具体命令类。因为针对每一个命令都需要设计一个具体命令类,因此某些系统可能需要大量具体命令类,这将影响命令模式的使用
五.应用场景
>系统需要将请求调用者和请求接收者解耦,使得调用者和接收者不直接交互。
>系统需要在不同的时间指定请求、将请求排队和执行请求。
>系统需要支持命令的撤销(Undo)操作和恢复(Redo)操作。
>系统需要将一组操作组合在一起,即支持宏命令