#include <iostream>
#include <memory>
#include <vector>
class Light {
public:
void on() {
std::cout << "💡 Light turned on (ON)" << std::endl;
}
void off() {
std::cout << "💡 Light turned off (OFF)" << std::endl;
}
};
class Command {
public:
virtual ~Command() = default;
virtual void execute() = 0;
virtual void undo() = 0;
};
class LightOnCommand : public Command {
private:
Light* light_;
public:
explicit LightOnCommand(Light* light) : light_(light) {}
void execute() override {
light_->on();
}
void undo() override {
light_->off();
}
};
class LightOffCommand : public Command {
private:
Light* light_;
public:
explicit LightOffCommand(Light* light) : light_(light) {}
void execute() override {
light_->off();
}
void undo() override {
light_->on();
}
};
class RemoteControl {
private:
std::vector<std::shared_ptr<Command>> history_;
public:
void executeCommand(std::shared_ptr<Command> cmd) {
cmd->execute();
history_.push_back(cmd);
}
void undoLastCommand() {
if (history_.empty()) {
std::cout << "⚠️ No command to undo." << std::endl;
return;
}
auto lastCmd = history_.back();
history_.pop_back();
lastCmd->undo();
}
};
int main() {
Light livingRoomLight;
auto lightOn = std::make_shared<LightOnCommand>(&livingRoomLight);
auto lightOff = std::make_shared<LightOffCommand>(&livingRoomLight);
RemoteControl remote;
std::cout << "=== Remote Control Operation Demo ===" << std::endl;
remote.executeCommand(lightOn);
remote.executeCommand(lightOff);
remote.undoLastCommand();
remote.undoLastCommand();
remote.undoLastCommand();
return 0;
}