[root@ ~/learn_code/design_pattern/19_order]$ cat order.cpp
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator> using namespace std; class Receiver
{
public:
void BakeMutton()
{
cout<< "烤羊肉"<< endl;
} void BakeChicken()
{
cout<< "烤鸡翅"<< endl;
}
}; class Command
{
public:
Command(Receiver* pstReceiver):m_pstReceiver(pstReceiver)
{ }
virtual void Excute() = ; protected:
Receiver* m_pstReceiver;
}; class ConcreteCommandA: public Command
{
public:
ConcreteCommandA(Receiver* pstReceiver):Command(pstReceiver)
{ }
virtual void Excute()
{
cout<< "ConcreteCommandA excuting......"<< endl;
m_pstReceiver->BakeMutton();
} }; class ConcreteCommandB: public Command
{
public:
ConcreteCommandB(Receiver* pstReceiver):Command(pstReceiver)
{ }
virtual void Excute()
{
cout<< "ConcreteCommandB excuting......"<< endl;
m_pstReceiver->BakeChicken();
}
}; class Invoke
{
public:
void Add(Command* pstCommand)
{
m_vecPstCommand.push_back(pstCommand);
}
void Remove(Command* pstCommand)
{
m_vecPstCommand.erase(find(m_vecPstCommand.begin(), m_vecPstCommand.end(), pstCommand));
}
void RemoveAll()
{
m_vecPstCommand.clear();
}
void Notify()
{
for (typeof(m_vecPstCommand.begin()) it = m_vecPstCommand.begin(); it != m_vecPstCommand.end(); ++it)
{
(*it)->Excute();
}
} private:
vector<Command*> m_vecPstCommand;
}; int main(int argc, char* argv[])
{
Receiver* pstReceiver = new Receiver();
Command* pstConcreteCommandA = new ConcreteCommandA(pstReceiver);
Command* pstConcreteCommandB = new ConcreteCommandB(pstReceiver);
Invoke* pstInvoke = new Invoke(); pstInvoke->Add(pstConcreteCommandA);
pstInvoke->Add(pstConcreteCommandA);
pstInvoke->Add(pstConcreteCommandB);
pstInvoke->Notify();
cout<< "------------------"<< endl<< endl; pstInvoke->Remove(pstConcreteCommandA); //撤销操作
pstInvoke->Remove(pstConcreteCommandB);
pstInvoke->Notify();
cout<< "------------------"<< endl<< endl; return ;
}
////////////////////////////////////////
[root@ ~/learn_code/design_pattern/19_order]$ ./order
ConcreteCommandA excuting......
烤羊肉
ConcreteCommandA excuting......
烤羊肉
ConcreteCommandB excuting......
烤鸡翅
------------------ ConcreteCommandA excuting......
烤羊肉
------------------