一、建立命令队列;二、可以将命令记入日志;三、接收请求的一方可以拒绝;四、添加一个新命令类不影响其它类;
命令模式把请求一个操作的对象与知道怎么操行一个操作的对象分开
命令模式感觉就是一个领导接受客户端的命令,让底下的人去做,但是比较特殊。继承命令
上图
上代码
- // Command.cpp : 定义控制台应用程序的入口点。
- //
- //************************************************************************/
- /* @filename Command.cpp
- @author wallwind
- @createtime 2012/10/24 00:00
- @function 命令模式
- @email wochenglin@qq.com
- */
- /************************************************************************/
- #include "stdafx.h"
- #include <iostream>
- #include <string>
- #include <vector>
- using namespace std;
- //烤肉师傅
- class Barbucer
- {
- public:
- void MakeMutton()
- {
- cout<<"烤羊肉"<<endl;
- }
- void MakeChickenWing()
- {
- cout<<"烤鸡翅膀"<<endl;
- }
- };
- //抽象命令类
- class Command
- {
- protected:
- Barbucer* receiver;
- public:
- Command(Barbucer* temp)
- {
- receiver = temp;
- }
- virtual void ExecuteCmd()=0;
- };
- //烤羊肉命令
- class BakeMuttonCmd : public Command
- {
- public:
- BakeMuttonCmd(Barbucer* temp) : Command(temp){}
- virtual void ExecuteCmd()
- {
- receiver->MakeMutton();
- }
- };
- //烤鸡翅
- class ChickenWingCmd : public Command
- {
- public:
- ChickenWingCmd(Barbucer* temp) : Command(temp){}
- virtual void ExecuteCmd()
- {
- receiver->MakeChickenWing();
- }
- };
- //服务员类
- class Waiter
- {
- protected:
- vector<Command*> m_commandList;
- public:
- void SetCmd(Command* temp)
- {
- m_commandList.push_back(temp);
- cout<<"增加定单"<<endl;
- }
- //通知执行
- void Notify()
- {
- vector<Command*>::iterator p=m_commandList.begin();
- while(p!=m_commandList.end())
- {
- (*p)->ExecuteCmd();
- p++;
- }
- }
- };
- int _tmain(int argc, _TCHAR* argv[])
- {
- //店里添加烤肉师傅、菜单、服务员等顾客
- Barbucer* barbucer=new Barbucer();
- Command* cmd= new BakeMuttonCmd(barbucer);
- Command* cmd2=new ChickenWingCmd(barbucer);
- Waiter* girl = new Waiter();
- //点菜
- girl->SetCmd(cmd);
- girl->SetCmd(cmd2);
- //服务员通知
- girl->Notify();
- return 0;
- return 0;
- }