#include <iostream>
#include <vector>
#include <memory>
using namespace std;
class Command {
public:
virtual void execute() = 0;
virtual ~Command() {}
};
class NoCommand : public Command {
public:
void execute() override {}
};
class Controller {
private:
vector<std::unique_ptr<Command>> onCommands;
vector<std::unique_ptr<Command>> offCommands;
int pre;
public:
Controller(vector<std::unique_ptr<Command>>&& onCommands, vector<std::unique_ptr<Command>>&& offCommands)
: onCommands(move(onCommands)), offCommands(move(offCommands)) {
pre = -1;
}
void execute(int i) {
assert(i < onCommands.size() && i >= 0);
onCommands[i]->execute();
pre = i;
}
void undo() {
if (pre >= 0) {
assert(pre < offCommands.size());
offCommands[pre]->execute();
pre = -1;
}
}
};
class Light {
public:
void on() {
cout << "light on" << endl;
}
void off() {
cout << "light off" << endl;
}
};
class LightOnCommand : public Command {
private:
Light light;
public:
void execute() override {
light.on();
}
};
class LightOffCommand : public Command {
private:
Light light;
public:
void execute() override {
light.off();
}
};
int main() {
vector<unique_ptr<Command>> onCommand;
onCommand.emplace_back(make_unique<LightOnCommand>());
vector<unique_ptr<Command>> offCommand;
offCommand.emplace_back(make_unique<LightOffCommand>());
Controller controller(move(onCommand), move(offCommand));
controller.execute(0);
controller.undo();
return 0;
}
c++ 命令模式
最新推荐文章于 2022-04-10 01:08:09 发布