| 名称 | Command |
| 结构 | ![]() |
| 意图 | 将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可撤消的操作。 |
| 适用性 |
|
| Code Example |
1 // Command2 ![]() 3 // Intent: "Encapsulate a request as an object, thereby letting you 4 // parameterize clients with different requests, queue or log 5 // requests, and support undoable operations". 6 ![]() 7 // For further information, read "Design Patterns", p233, Gamma et al.,8 // Addison-Wesley, ISBN:0-201-63361-29 ![]() 10 /* Notes:11 * Commands are at the heart of a modern GUI app. 12 * They must be nameable, undoable, recordable, 13 * configurable, executable and repeatable. 14 * 15 * In addition to the command here, a command type could also be useful.16 * It could store the name of a command, information about its icon, etc. 17 */18 19 namespace Command_DesignPattern20 {21 using System;22 ![]() 23 abstract class Command 24 {25 abstract public void Execute();26 protected Receiver r;27 public Receiver R28 {29 set 30 {31 r = value; 32 }33 }34 }35 ![]() 36 class ConcreteCommand : Command37 {38 override public void Execute()39 {40 Console.WriteLine("Command executed");41 r.InformAboutCommand();42 }43 }44 ![]() 45 class Receiver 46 {47 public void InformAboutCommand()48 {49 Console.WriteLine("Receiver informed about command");50 }51 52 }53 ![]() 54 class Invoker 55 {56 private Command command;57 public void StoreCommand(Command c)58 {59 command = c;60 }61 public void ExecuteCommand()62 {63 command.Execute();64 } 65 }66 ![]() 67 /// <summary>68 /// Summary description for Client.69 /// </summary>70 public class Client71 {72 public static int Main(string[] args)73 { 74 // Set up everything75 Command c = new ConcreteCommand();76 Receiver r = new Receiver();77 c.R = r;78 Invoker i = new Invoker();79 i.StoreCommand(c);80 ![]() 81 // now let application run82 ![]() 83 // the invoker is how the command is exposed for the end-user 84 // (or a client) initiates the command, 85 // (e.g. toolbar button, menu item)86 ![]() 87 i.ExecuteCommand();88 ![]() 89 return 0;90 }91 }92 }93 ![]() 94 ![]() |




* Commands are at the heart of a modern GUI app.


}