(1) receiver: 知道如何執行該命令
1: class Receiver
2: {
3: public void Action(string action)
4: {
5: Console.WriteLine("{0} 動作執行", action);
6: }
7: }
(2) Command: 一個抽象指令,擁有一個Receiver實體,在創建子階段綁定。
1: abstract class Command
2: {
3: protected Receiver receiver;
4: public Command(Receiver receiver)
5: {
6: this.receiver = receiver;
7: }
8: abstract public void Execute();
9: }
(3) Concrete Command: 繼承Command
1: class CoffeeCommand : Command
2: {
3: public CoffeeCommand(Receiver receiver) : base(receiver) { }
4: public override void Execute()
5: {
6: receiver.Action("泡咖啡...");
7: }
8: }
9: class TeaCommand:Command
10: {
11: public TeaCommand(Receiver receiver) : base(receiver) { }
12: public override void Execute()
13: {
14: receiver.Action("泡茶...");
15: }
16: }
(4) invoker: 請求一個命令的執行,擁有一個Command實體,利用SetCommand(…)接收一個命令(Concrete Command)以及ExecuteCommand執行命令。
1: class Invoker
2: {
3: Command command;
4: public void SetCommand(Command command) { this.command = command; }
5: public void ExecuteCommand() { command.Execute(); }
6: }
客戶端
1. 隨機挑選命令coffee or tea,再由invoker指派(SetCommand),並執行invoker.Execute()
2. invoker.Execute其實是invoker內存command實體去動作,tea/coffee都是由Command類別衍伸出來的實體,因此包含抽象方法Execute(),tea/coffee會各自覆寫override。
3. 觀察CoffeeCommand或是TeaCommand如何執行Execute,其實是由receiver去執行(Action(…))完成的。
4. Receiver可以升級為超類別,然後繼承Receiver的子類別(Concrete Receiver)可以對應不同的Concrete Command()。也就是不同命令由不同Action去完成。
1. 隨機產生1~10亂數。
2. Line 11: 如果亂數值(v)<5則invoker.SetCommand(coffee)選擇咖啡命令,否則選擇tea。
3. Line 18: 執行命令 invoker.ExecuteCommand()
1: Receiver r = new Receiver();
2: Command coffee = new CoffeeCommand(r);
3: Command tea = new TeaCommand(r);
4: Invoker invoker = new Invoker();
5: Random rand = new Random();
6: int v = 0;
7: for (int i=0; i<10; i++)
8: {
9: v = rand.Next(11);
10: Console.Write("#{0}, ", i);
11: if(v<5)
12: {
13: invoker.SetCommand(coffee);
14: }else
15: {
16: invoker.SetCommand(tea);
17: }
18: invoker.ExecuteCommand();
19: }
20: Console.Read();
留言列表