命令模式

发布于:2024-04-18 ⋅ 阅读:(17) ⋅ 点赞:(0)

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

命令模式的好处:
1、它能较容易地设计一个命令队列;
2、在需要的情况下,可以较容易地将命令记入日志;
3、允许接收请求的一方决定是否要否决请求;
4、可以容易地实现对请求的撤销和重做;
5、由于加进新的具体命令类不影响其他的类,因此增加新的具体命令类很容易;
6、命令模式把请求一个操作的对象与知道怎么执行一个操作的对象分割开。

在这里插入图片描述
Invoker.h

#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

#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

#ifndef RECIEVER_H
#define RECIEVER_H

#include <iostream>

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

#endif //RECIEVER_H

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