命令模式
简介
:命令模式将一个请求封装为一个对象,从而使你可以用不同的请求对客户进行参数化,对请求排队或记录请求日志,以及支持可撤销的操作。
人话
: 总体来说, 就是一个命令类, 一个执行类, 命令类包括执行类, 然后在外部添加一个总的管理类, 来管理命令列表
与其他模式比较
与修饰器模式对比
:与修饰器模式非常像, 就是在真正的执行者外面包裹一层修饰类, 只不过这里叫做命令类
比如做日志操作, 事务操作, 修饰模式也是可以的啊, 甚至结构都差不多, 唯一不同
的就是外面多了一个总的控制类
优点
: 不过还是有好处的, 就是将操作 和 执行者解耦了, 比如我想执行一个唱歌命令, 可以解耦的指定不通的类来唱, 没有写死
代码
class Executor
{
public:void log(){cout << "记录日志" << endl;}void send(){cout << "向服务端发送数据" << endl;}
};class Command
{
private:Executor* e;
public:inline Executor* get_executor() { return e; };Command(Executor* _e) : e(_e) {};virtual void run() = 0;
};class LogCommand : public Command
{
public:LogCommand(Executor* _e) : Command(_e) {};void run() override{get_executor()->log();}
};class NetCommand : public Command
{
public:NetCommand(Executor* _e) : Command(_e) {};void run() override{get_executor()->send();}
};class Invoker
{
private:vector<Command*> _commands;
public:void add_command(Command* c) { _commands.push_back(c); };void execute_commands(){for (Command* c : _commands)c->run();}
};int main()
{Invoker* invoker = new Invoker();Executor* e = new Executor();LogCommand* lc = new LogCommand(e);NetCommand* nc = new NetCommand(e);invoker->add_command(lc);invoker->add_command(nc);invoker->execute_commands();return 0;
}
执行结果