设计模式 Design Parttern ——命令模式Command http://blog.csdn.net/leeidea/ 1:头文件 #ifndef _COMMAND_H_VANEY_ #define _COMMAND_H_VANEY_ #include <iostream> using namespace std; /****************************************************************** 名称 :Command.h 版本 :1.00 描述 :演示命令模式的概念 作者 :vaney.li@gmail.com http://blog.csdn.net/leeidea 日期 :2010年10月22日 版权 :vaney.li@gmail.com http://blog.csdn.net/leeide ******************************************************************/ /* 官方解释:The Command pattern allows requests to be encapsulated as objects, thereby allowing clients to be parameterized with different requests. 我的理解:命令模式由三大部分组成,命令组,调用者,响应者,调用者不直接操作响应者,调用 可以合理的组织命令队列,然后执行该队列 */ //响应者 class CReceiver { public: CReceiver() { cout << "CReceiver()" << endl; } virtual ~CReceiver() { cout << "~CReceiver()" << endl; } public: //需要子类实现的方法 virtual void DO1() { cout << "CReceiver DO1()" << endl; } virtual void DO2() { cout << "CReceiver DO2()" << endl; } virtual void DO3() { cout << "CReceiver DO3()" << endl; } }; //抽象命令 class CCommand { public: CCommand(CReceiver* rcver) { m_rcver = rcver; cout << "CCommand()" << endl; } virtual ~CCommand() { if(m_rcver) delete m_rcver; m_rcver = 0; cout << "~CCommand()" << endl; } public: //需要子类实现的方法 virtual void Execute() = 0; protected: CReceiver* m_rcver; }; //命令1 执行接受者的DO1行为 class CCommand1 : public CCommand { public: CCommand1(CReceiver* rcver):CCommand(rcver) { cout << "CCommand1()" << endl; } virtual ~CCommand1() { if(m_rcver) delete m_rcver; m_rcver = 0; cout << "~CCommand1()" << endl; } public: //需要子类实现的方法 virtual void Execute() { if(m_rcver) m_rcver->DO1(); cout << "CCommand1 DO1()" << endl; } }; //命令2 执行接受者的DO2行为 class CCommand2 : public CCommand { public: CCommand2(CReceiver* rcver):CCommand(rcver) { cout << "CCommand1()" << endl; } virtual ~CCommand2() { if(m_rcver) delete m_rcver; m_rcver = 0; cout << "~CCommand2()" << endl; } public: //需要子类实现的方法 virtual void Execute() { if(m_rcver) m_rcver->DO2(); cout << "CCommand2 DO2()" << endl; } }; //使用者 #define CMD_NUMS 10 class CUser { CCommand *_cmds[CMD_NUMS]; int index; public: CUser():index(0) { cout << "CUser()" << endl; } virtual ~CUser() { for(int i = 0; i < index; i++) { delete _cmds[i]; } cout << "~CUser()" << endl; } public: void SetCommand(CCommand* cmd) { if(index < CMD_NUMS) _cmds[index++] = cmd; } void Execute() { if(index) { for(int i = 0; i < index; i++) { _cmds[i]->Execute(); } } } }; #define C_API extern "C" //用户 C_API int UsingCM(); #endif 2:源文件 #include "Command.h" C_API int UsingCM() { //创建接受者 CReceiver* rever = new CReceiver(); //创建具体命令 CCommand1* cmd1 = new CCommand1(rever); CCommand2* cmd2 = new CCommand2(rever); //创建用户 CUser* user = new CUser(); //创建命令列表 user->SetCommand(cmd1); user->SetCommand(cmd2); //执行 user->Execute(); return 1; } 3:用户文件main.c extern int UsingCM(); //系统默认入口 int _tmain(int argc, _TCHAR* argv[]) { return UsingCM(); }