1.命令模式简介
将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化,对请求排队或记录请求日志。以及支持可撤销的操作。
2.源码实现
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
//烤肉师傅
class BarbecueMaster
{
public:
void MakeMutton()
{
cout << "烤羊腿喽" << endl;
}
void MakeChiken()
{
cout << "烤鸡肉喽" << endl;
}
};
//命令类
class Command
{
protected:
BarbecueMaster *m_master;
public:
Command(BarbecueMaster *p)
{
m_master = p;
}
virtual void executeCmd() = 0;
};
class CommandMutton : public Command
{
public:
CommandMutton(BarbecueMaster *p) : Command(p) {};
void executeCmd()
{
m_master->MakeMutton();
}
};
class CommandChiken : public Command
{
public:
CommandChiken(BarbecueMaster *p) : Command(p) {};
void executeCmd()
{
m_master->MakeChiken();
}
};
//服务员
class Waiter
{
private:
vector<Command *> m_vec;
public:
~Waiter()
{
for(auto it=m_vec.begin(); it!=m_vec.end(); it++)
{
delete(*it);
}
m_vec.clear();
}
void add(Command *p)
{
m_vec.push_back(p);
}
void remove(Command *p)
{
for(auto it=m_vec.begin(); it!=m_vec.end(); it++)
{
if(*it == p)
{
delete(*it);
break;
}
}
}
void submitCmd()
{
for(auto it=m_vec.begin(); it!=m_vec.end(); it++)
{
(*it)->executeCmd();
}
}
};
int main(int argc, char **argv)
{
Waiter *pWaiter = new Waiter();
BarbecueMaster *pBarbecueMaster = new BarbecueMaster();
pWaiter->add(new CommandMutton(pBarbecueMaster));
pWaiter->add(new CommandChiken(pBarbecueMaster));
pWaiter->add(new CommandMutton(pBarbecueMaster));
pWaiter->submitCmd();
delete pBarbecueMaster;
delete pWaiter;
return 0;
}
3.编译源码
$ g++ -o example example.cpp
4.运行及其结果
$ ./example
烤羊腿喽
烤鸡肉喽
烤羊腿喽
网友评论