将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可撤销的操作。在OOP中,一切都是对象,将请求封装成对象,符合OOP的设计思想,当将客户的单个请求封装成对象以后,我们就可以对这个请求存储更多的信息,使请求拥有更多的能力;命令模式同样能够把请求发送者和接收者解耦,使得命令发送者不用去关心请求将以何种方式被处理。
#include <iostream>
using namespace std;
#include <vector>
class Barbecuer
{
public:
void makeChicken()
{
cout << "makeChicken........" << endl;
}
void makeDuck()
{
cout << "makeDuck.........." << endl;
}
};
class Command
{
public:
virtual void ExecCommand() = 0;
private:
Barbecuer *m_barbecuer;
};
class ChickenCommand :public Command
{
public:
ChickenCommand(Barbecuer *bar) :m_barbecuer(bar)
{
}
void ExecCommand()
{
m_barbecuer->makeChicken();
}
private:
Barbecuer *m_barbecuer;
};
class DuckCommand :public Command
{
public:
DuckCommand(Barbecuer *bar) :m_barbecuer(bar)
{
}
void ExecCommand()
{
m_barbecuer->makeDuck();
}
private:
Barbecuer *m_barbecuer;
};
class Waiter
{
public:
void addCommand(Command *pCmd)
{
m_vec.push_back(pCmd);
}
void delCommand(Command *pCmd)
{
for (vector<Command*>::iterator itor = m_vec.begin(); itor != m_vec.end();)
{
if (*itor == pCmd)
{
itor = m_vec.erase(itor);
}
else
{
itor++;
}
}
}
void notify()
{
for (vector<Command*>::iterator itor = m_vec.begin(); itor != m_vec.end(); itor++)
{
(*itor)->ExecCommand();
}
}
private:
vector<Command*> m_vec;
};
int main()
{
Barbecuer *bar = new Barbecuer;
ChickenCommand *cmd1 = new ChickenCommand(bar);
DuckCommand *cmd2 = new DuckCommand(bar);
Waiter *pWaiter = new Waiter;
pWaiter->addCommand(cmd1);
pWaiter->addCommand(cmd2);
pWaiter->notify();
return 0;
}