欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 明星 > 命令模式详解

命令模式详解

2024/10/24 7:24:28 来源:https://blog.csdn.net/qq_40666620/article/details/141604802  浏览:    关键词:命令模式详解

命令模式

简介:命令模式将一个请求封装为一个对象,从而使你可以用不同的请求对客户进行参数化,对请求排队或记录请求日志,以及支持可撤销的操作。

人话: 总体来说, 就是一个命令类, 一个执行类, 命令类包括执行类, 然后在外部添加一个总的管理类, 来管理命令列表

与其他模式比较

与修饰器模式对比:与修饰器模式非常像, 就是在真正的执行者外面包裹一层修饰类, 只不过这里叫做命令类
比如做日志操作, 事务操作, 修饰模式也是可以的啊, 甚至结构都差不多, 唯一不同的就是外面多了一个总的控制类

优点: 不过还是有好处的, 就是将操作 和 执行者解耦了, 比如我想执行一个唱歌命令, 可以解耦的指定不通的类来唱, 没有写死

代码

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;
}

执行结果
在这里插入图片描述

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com