• 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)操作。
>系统需要将一组操作组合在一起,即支持宏命令