设计模式之命令模式
1 class Program 2 { //这个相当于饭店里 服务员记下客户的请求命令, 然后交给 厨师去执行请求 3 static void Main(string[] args) 4 { 5 Barbucure bar = new Barbucure(); 6 Command cc = new BakeMuttonCommand(bar); 7 Command c2 = new BakeChilkenCommand(bar); 8 Waiter w = new Waiter(); 9 w.SetCommand(cc); 10 w.SetCommand(c2); 11 12 w.Notify(); 13 14 Console.Read(); 15 } 16 } 17 18 public abstract class Command 19 { 20 protected Barbucure receiver; //请求的执行者 类似于 厨师 21 public Command(Barbucure receiver) //实例化 Barbucure 对象 22 { 23 this.receiver = receiver; 24 } 25 public abstract void ExecuteCommand(); 26 } 27 class BakeMuttonCommand : Command 28 { 29 public BakeMuttonCommand(Barbucure bar):base(bar) 30 { 31 } 32 public override void ExecuteCommand() //调用厨师 的方法 33 { 34 receiver.BakeMutton(); 35 } 36 } 37 38 class BakeChilkenCommand : Command 39 { 40 public BakeChilkenCommand(Barbucure bar) 41 : base(bar) 42 { 43 } 44 public override void ExecuteCommand() 45 { 46 receiver.BakeChilken(); 47 } 48 } 49 50 class Waiter //相当于 服务员 可以记下客户的请求,交给厨师执行 51 { 52 //private Command cmd; 53 //public Waiter(Command cmd) 54 //{ 55 // this.cmd = cmd; 56 //} 57 //public void Notify() //通知厨师执行方法。 58 //{ 59 // cmd.ExecuteCommand(); 60 //} 61 List<Command> listCommand = new List<Command>(); 62 public void SetCommand(Command cmd) 63 { 64 listCommand.Add(cmd); 65 } 66 67 public void RemoveCommand(Command cmd) 68 { 69 listCommand.Remove(cmd); 70 } 71 72 public void Notify() 73 { 74 foreach (var item in listCommand) 75 { 76 item.ExecuteCommand(); 77 } 78 } 79 80 } 81 82 public class Barbucure //厨师的具体执行方法 83 { 84 public void BakeMutton() 85 { 86 Console.WriteLine("烤羊肉"); 87 } 88 89 public void BakeChilken() 90 { 91 Console.WriteLine("烤鸡翅"); 92 } 93 }