结构 | |
意图 | 将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可撤消的操作。 |
适用性 |
|
1 using System; 2 3 abstract class Command 4 { 5 abstract public void Execute(); 6 protected Receiver r; 7 public Receiver R 8 { 9 set 10 {11 r = value; 12 }13 }14 }15 16 class ConcreteCommand : Command17 {18 override public void Execute()19 {20 Console.WriteLine("Command executed");21 r.InformAboutCommand();22 }23 }24 25 class Receiver 26 {27 public void InformAboutCommand()28 {29 Console.WriteLine("Receiver informed about command");30 }31 32 }33 34 class Invoker 35 {36 private Command command;37 public void StoreCommand(Command c)38 {39 command = c;40 }41 public void ExecuteCommand()42 {43 command.Execute();44 } 45 }46 47 ///48 /// Summary description for Client.49 /// 50 public class Client51 {52 public static int Main(string[] args)53 { 54 // Set up everything55 Command c = new ConcreteCommand();56 Receiver r = new Receiver();57 c.R = r;58 Invoker i = new Invoker();59 i.StoreCommand(c);60 61 // now let application run62 63 // the invoker is how the command is exposed for the end-user 64 // (or a client) initiates the command, 65 // (e.g. toolbar button, menu item)66 67 i.ExecuteCommand();68 69 return 0;70 }71 }