设计模式-命令模式
程序员文章站
2024-02-07 23:06:58
...
命令模式是将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可撤销的操作。
其UML类图如下:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// 烤肉师傅
class doctor
{
public:
void make_eye()
{
std::cout << "眼科" << std::endl;
}
void make_ear()
{
std::cout << "耳科" << std::endl;
}
};
// 命令类
class Command
{
protected:
doctor * m_doc;
public:
Command(doctor * p)
{
m_doc = p;
}
virtual void make() = 0;
};
class Command1 : public Command
{
public:
Command1(doctor * p) : Command(p) {}
void make()
{
m_doc->make_eye();
}
};
class Command2 : public Command
{
public:
Command2(doctor * p) : Command(p) {}
void make()
{
m_doc->make_ear();
}
};
// 服务员
class nurse
{
private:
std::vector<Command *> m_vec;
public:
~nurse()
{
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 submit()
{
for (auto it = m_vec.cbegin(); it != m_vec.cend(); it++)
{
(*it)->make();
}
}
};
int main() {
nurse * nur = new nurse();
doctor * d = new doctor();
nur->add(new Command1(d));
nur->add(new Command2(d));
nur->submit();
delete nur;
delete d;
return 0;
}