命令模式

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

命令模式的好处:

1、它能较容易地设计一个命令队列;

2、在需要的情况下,可以较容易地将命令记入日志;

3、允许接收请求的一方决定是否要否决请求;

4、可以容易地实现对请求的撤销和重做;

5、由于加进新的具体命令类不影响其他的类,因此增加新的具体命令类很容易;

6、命令模式把请求一个操作的对象与知道怎么执行一个操作的对象分割开。

Invoker.h

cpp 复制代码
#ifndef INVOKER_H
#define INVOKER_H

#include "Command.h"
#include <list>

using namespace std;

class Invoker {
private:
    list<Command *> commands;
public:
    void setCommand(Command *c) {
        commands.push_back(c);
    }

    void Notify() {
        for (auto c = commands.begin(); c != commands.end(); c++) {
            (*c)->Excute();
        }
    }
};

#endif //INVOKER_H

Command.h

cpp 复制代码
#ifndef COMMAND_H
#define COMMAND_H

#include "Reciever.h"

class Command {
public:
    virtual void Excute() = 0;
    virtual void setReceiver(Receiver* r) = 0;
    virtual ~Command(){};
};

class ConcreteCommand : public Command {
private:
    Receiver* receiver;
public:
    void setReceiver(Receiver* r) {
        receiver = r;
    }
    void Excute() {
        receiver->Action();
    }
};

#endif //COMMAND_H

Receiver.h

cpp 复制代码
#ifndef RECIEVER_H
#define RECIEVER_H

#include <iostream>

class Receiver {
public:
    void Action() {
        std::cout << "Receiver" << std::endl;
    }
};

#endif //RECIEVER_H

main.cpp

cpp 复制代码
#include <iostream>
#include "Command.h"
#include "Invoker.h"

using namespace std;

int main() {
    Command* c = new ConcreteCommand();
    Receiver* r = new Receiver();
    c->setReceiver(r);

    Invoker i;
    i.setCommand(c);
    i.Notify();   // Receiver
    return 0;
}
相关推荐
我有一棵树4 小时前
基于 Vue3 动态组件的弹框流程管理:命令模式事件
命令模式
__万波__1 天前
二十三种设计模式(十四)--命令模式
java·设计模式·命令模式
⑩-3 天前
Java设计模式-命令模式
java·设计模式·命令模式
Yeniden3 天前
Deepeek用大白话讲解 --> 命令模式(企业级场景1,智能家居遥控器2,撤销重做3,宏命令4)
智能家居·命令模式
小灰灰搞电子4 天前
Qt 重写QRadioButton实现动态radioButton源码分享
开发语言·qt·命令模式
小灰灰搞电子5 天前
Qt 实现炫酷锁屏源码分享
开发语言·qt·命令模式
一只小bit5 天前
Qt Widget 控件介绍:覆盖常用属性及API
开发语言·c++·qt·命令模式·cpp
iFlow_AI6 天前
iFlow CLI 实战案例|生产级 Agent 聊天应用——Chatbot
交互·ai编程·命令模式·iflow·iflow cli·iflowcli
道19938 天前
QT 工程中快速实现中英文切换(含动态切换)
命令模式
fpl11168 天前
npm :无法加载文件 D:\...\nodejs\npm.ps1,因为在此系统上禁止运行脚本
前端·vscode·npm·node.js·命令模式