【C++】【设计模式】命令模式


#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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值