#include <iostream>
#include <vector>
#include <string>
class TV {
public:
void turnOn() { std::cout << "TV turned on" << std::endl; }
void turnOff() { std::cout << "TV turned off" << std::endl; }
void changeChannel(int channel) { std::cout << "Channel changed to " << channel << std::endl; }
};
class Command {
public:
virtual ~Command() {}
virtual void execute() = 0;
virtual void undo() = 0;
};
class TurnOnCommand : public Command {
public:
TurnOnCommand(TV& tv) : m_tv(tv) {}
void execute() override { m_tv.turnOn(); }
void undo() override { m_tv.turnOff(); }
private:
TV& m_tv;
};
class TurnOffCommand : public Command {
public:
TurnOffCommand(TV& tv) : m_tv(tv) {}
void execute() override { m_tv.turnOff(); }
void undo() override { m_tv.turnOn(); }
private:
TV& m_tv;
};
class ChangeChannelCommand : public Command {
public:
ChangeChannelCommand(TV& tv, int channel) : m_tv(tv), m_channel(channel) {}
void execute() override {
m_previousChannel = getCurrentChannel();
m_tv.changeChannel(m_channel);
}
void undo() override { m_tv.changeChannel(m_previousChannel); }
private:
int getCurrentChannel() {
// Code to get the current channel from the TV
return 0;
}
TV& m_tv;
int m_channel;
int m_previousChannel;
};
class RemoteControl {
public:
void setCommand(Command* command) { m_command = command; }
void pressButton() {
m_command->execute();
m_commands.push_back(m_command);
}
void undo() {
if (!m_commands.empty()) {
m_commands.back()->undo();
m_commands.pop_back();
}
}
private:
Command* m_command;
std::vector<Command*> m_commands;
};
int main() {
TV tv1, tv2;
TurnOnCommand turnOn1(tv1);
TurnOffCommand turnOff1(tv1);
ChangeChannelCommand channel1(tv1, 5);
TurnOnCommand turnOn2(tv2);
TurnOffCommand turnOff2(tv2);
ChangeChannelCommand channel2(tv2, 10);
RemoteControl remote;
remote.setCommand(&turnOn1);
remote.pressButton();
remote.setCommand(&turnOff1);
remote.pressButton();
remote.setCommand(&channel1);
remote.pressButton();
remote.setCommand(&turnOn2);
remote.pressButton();
remote.setCommand(&turnOff2);
remote.pressButton();
remote.setCommand(&channel2);
remote.pressButton();
std::cout << "Undoing last command..." << std::endl;
remote.undo();
return 0;
}
【C++】【设计模式】命令模式
最新推荐文章于 2024-07-25 17:57:45 发布