命令模式是将请求封装为一个对象,以便能够参数化请求,实现请求日志支持可撤销操作。有时候必须向对象提交请求但是不知道请求接受者的信息。例如在MONGODB里面对于客户端发来的请求都封装成request对象,不同的操作调用不同的策略对象去执行。这样请求可以被存储和传递。
抽象一个command对象提供公共操作接口,譬如最基本的execute,undo等。在这个基础上派生子类执行特定的操作命令,调用接受者相应的操作实现execute等接口。一些情况下,comcreteCommand自己实现操作,一些情况下只需要指定接受者对象。
示例代码:
1 #include <list>
2 using namespace std;
3 class command {
4 public:
5 virtual ~command(){};
6
7 virtual void execute()=0;
8 protected:
9 command(){};
10 };
11
12 class openCommand : public command{
13 public:
14 virtual void execute() { say(); };
15 void say() { printf("openCmd\n"); };
16 };
17
18 class pasteCommand : public command {
19 public:
20 virtual void execute() { say(); };
21 void say() { printf("pasteCmd\n"); }
22 };
23
24 class handler {
25 public:
26 void addCommand(command* c) { _cmds.push_back(c); };
27 void deal(){
28 command* pCmd=NULL;
29 if(!_cmds.empty()) {
30 _cmds.front()->execute();
31 _cmds.pop_front();
32 }
33 };
34 private:
35 list<command*> _cmds;
36 };
37
38
39 int _tmain(int argc, _TCHAR* argv[])
40 {
41 handler h;
42 openCommand* pOpenCmd=new openCommand;
43 pasteCommand* pPasteCmd=new pasteCommand;
44
45 h.addCommand(pOpenCmd);
46 h.addCommand(pPasteCmd);
47 h.deal();
48 h.deal();
49
50 delete pOpenCmd;
51 delete pPasteCmd;
52 getchar();
53 return 0;
54 }