1. Client创建一个ConcreteCommand对象并指定他的Receiver对象
2. 某个Invoker对象存储该ConcreteCommand对象
3. 该Invoker通过调用Command对象的Execute操作来提交一个请求。若该命令是可撤销的,ConcreteCommand就在执行Execute操作之前存储当前状态以用于取消该命令
4. ConcreteCommand对象对调用它的Receiver的一些操作以执行该请求
// Command.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <list> #include <iostream> using namespace std; class Barbecur{ public: void bakefish(){ cout<<"开始烤鱼"<<endl; } void bakemeat(){ cout<<"开始烤肉"<<endl; } }; class Command{ public: Command(Barbecur * p){ m_p = p; } virtual void execcommand() = 0; virtual ~Command(){} protected: Barbecur * m_p; }; class BakeFishCommand:public Command{ public: BakeFishCommand(Barbecur * p):Command(p){} void execcommand(){ this->m_p->bakefish(); } }; class BakeMeatCommand:public Command{ public: BakeMeatCommand(Barbecur *p):Command(p){} void execcommand(){ this->m_p->bakemeat(); } }; class Waiter{ public: void addcommand(Command * p ){ m_list.push_back(p); } void cancelcommand(Command * p){ m_list.remove(p); } void notify(){ list<Command * >::iterator it; for(it = m_list.begin();it!=m_list.end();it++){ (*it)->execcommand(); } } private: list<Command *> m_list; }; int main(int argc, char* argv[]) { Barbecur * cooker = new Barbecur; Command * pfish = new BakeFishCommand(cooker); Command * pmeat = new BakeMeatCommand(cooker); Waiter * pwaiter = new Waiter; pwaiter->addcommand(pfish); pwaiter->addcommand(pmeat); pwaiter->notify(); pwaiter->cancelcommand(pfish); pwaiter->notify(); delete cooker; delete pfish; delete pmeat; delete pwaiter; return 0; }