设计模式-命令模式

来源:互联网 发布:工程软件开发技术 编辑:程序博客网 时间:2024/04/29 13:56
 

1. 命令模式的角色组成

1)  命令角色(Command):生命执行操作的接口。接口或抽象类来实现。

2)  具体命令角色(Concrete Command):将一个接收者对象绑定于一个动作;调用接收者相应的操作,以实现命令角色声明的执行操作的接口。

3)  客户角色(Client): 创建一个具体命令对象(并可以设定它的接收者)。

4)  请求者角色(Invoker):调用命令对象执行这个请求。

5)  接收者角色(Receiver):知道如何实施与执行一个请求相关的操作。任何类都可能作为一个接收者。

 

命令模式类图:

暂缺

 

 

2. 应用实例

(本人感觉这个例子比较能切合类图的含义)

场景:某日,我去饭店吃饭,进去后对服务员说:“我要一个三明治”,服务员对厨师喊,“三明治一份”,我然后又说:“再来个煮鸡蛋。”服务员对厨师喊,“煮鸡蛋一份”,我说:“没了,就这些”,服务员喊,“就这些了,开做。”于是厨师开始做。

 

  1. #include "stdafx.h"
  2. #include <algorithm>
  3. #include <map>
  4. #include <iostream>
  5. using namespace std;
  6. //ICommand相当于服务员喊话的标准
  7. class ICommand
  8. {
  9. public:
  10.     virtual void Execute()
  11.     {
  12.     };
  13. };
  14. //Receiver 相当于厨师
  15. class Receiver
  16. {
  17.     //做鸡蛋
  18. public:
  19.     void CookEgg() 
  20.     { 
  21.         cout << "Cooking an egg./n"
  22.     }
  23.     //做三明治
  24.     void CookSandwich() 
  25.     { 
  26.         cout << "Cooking a sandwich./n"
  27.     }
  28. };
  29. //喊话内容:鸡蛋
  30. class CookEggCommand : public ICommand
  31. {
  32. protected:
  33.     Receiver* receiver;
  34. public:
  35.     CookEggCommand(Receiver* receiver)
  36.     {
  37.         this->receiver = receiver;
  38.     }
  39.     void Execute()
  40.     {
  41.         receiver->CookEgg();
  42.     }
  43. };
  44. //喊话内容:三明治
  45. class CookSandwichCommand : public ICommand
  46. {
  47. protected:
  48.     Receiver* receiver;
  49. public:
  50.     CookSandwichCommand(Receiver* receiver)
  51.     {
  52.         this->receiver = receiver;
  53.     }
  54.     void Execute()
  55.     {
  56.         receiver->CookSandwich();
  57.     }
  58. };
  59. //Invoker 相当于服务员
  60. class Invoker
  61. {
  62. public:
  63.     int iCount;
  64.     map<int, ICommand*> commands;
  65.     Invoker()
  66.     {
  67.         iCount = 0;
  68.     }
  69.     //喊话
  70.     void SetCommand(ICommand* command)
  71.     {
  72.         commands.insert(map<int, ICommand*>::value_type(iCount, command));
  73.         iCount++;
  74.     }
  75.     
  76.     //执行喊话内容
  77.     void ExecuteCommand()
  78.     {
  79.         int i;
  80.         ICommand* cmd;
  81.         for(i = 0; i < iCount; i++)
  82.         {
  83.             cmd = commands[i];
  84.             cmd->Execute();
  85.         }
  86.     }
  87. };
  88. int main()
  89. {
  90.     Receiver receiver;
  91.     ICommand* egg= new CookEggCommand(&receiver);
  92.     ICommand* sandwich = new CookSandwichCommand(&receiver);
  93.     Invoker invoker;
  94.     //服务员喊话,三明治一份
  95.     invoker.SetCommand(sandwich);
  96.     //服务员喊话,鸡蛋一份
  97.     invoker.SetCommand(egg);
  98.     //服务员喊话,没有别的了,做吧。
  99.     invoker.ExecuteCommand();
  100.     
  101.     delete egg;
  102.     delete sandwich;
  103.     return 1;
  104. }
原创粉丝点击