命令模式是一种行为设计模式,它将请求封装成一个对象,从而允许您根据不同的请求将客户端参数化,将请求排入队列或记录请求日志,并支持可撤销的操作。
在命令模式中,有以下几个关键角色:
#include <iostream>
#include <string>
#include <queue>
// 命令接口
class Command {
public:
virtual ~Command() {}
virtual void execute() const = 0;
};
// 接收者类
class Receiver {
public:
void AddMoney() {
std::cout << "给玩家加金币" << std::endl;
}
void AddDiamond() {
std::cout << "给玩家加钻石" << std::endl;
}
};
// 具体命令类
class AddMoneyCommand : public Command {
private:
* receiver_;
Receiverpublic:
(Receiver *receiver) : receiver_(receiver) {}
AddMoneyCommandvoid execute() const override {
// 在这里执行具体的操作
receiver_->AddMoney();
}
};
class AddDiamondCommand : public Command {
private:
* receiver_;
Receiverpublic:
(Receiver* receiver) : receiver_(receiver) {}
AddDiamondCommandvoid execute() const override {
// 在这里执行具体的操作
receiver_->AddDiamond();
}
};
// 调用者类
class Invoker {
private:
std::queue<Command*> queue_;
public:
void AddCommand(Command* command) {
queue_.push(command);
}
void executeCommand() {
while (queue_.empty() == false) {
* command = queue_.front();
Command->execute();
commandqueue_.pop();
}
}
};
int main() {
// 创建接收者对象
;
Receiver receiver// 创建具体命令对象并绑定接收者
(&receiver);
AddDiamondCommand command1(&receiver);
AddMoneyCommand command2;
Invoker invoker.AddCommand(&command1);
invoker.AddCommand(&command2);
invoker.executeCommand();
invokerreturn 0;
}
/*
给玩家加钻石
给玩家加金币
*/