首页 > 编程笔记 > C++笔记 阅读:24

命令模式详解(附带C++实例)

封装是面向对象编程的基石之一,它不仅保护了数据的安全性,也使得代码更易于管理和扩展。在设计模式中,封装行为的思想被运用于多种模式中,其中就包括命令模式。

命令模式将请求或简单操作封装成对象,允许用户以参数的形式在程序中存储、传递和返回消息或请求调用。这种模式的核心在于分离了发送命令的对象和接收并执行命令的对象。

命令模式的应用场景和优势如下:

命令模式的设计准则

命令模式主要是将操作封装为对象,允许将函数调用、请求或某些操作延迟到其他对象中进行处理。

其核心设计准则包括:

命令模式中的角色

命令模式主要包括以下几个角色:
命令模式的活动图如下图所示,展示了这些角色如何交互。


图 1 命令模式

C++实现命令模式

下面是一个使用命令模式的 C++ 示例代码。在这个例子中,我们将模拟一个简单的遥控器,可以控制灯的开和关。代码中将展示命令模式的各个角色。
#include <iostream>
#include <vector>
#include <memory>

// 命令接口
class Command {
public:
    virtual ~Command() {}
    virtual void execute() = 0;
};

// 接收者类
class Light {
public:
    void turnOn() {
        std::cout << "Light is on." << std::endl;
    }
    void turnOff() {
        std::cout << "Light is off." << std::endl;
    }
};

// 具体命令类:开灯
class LightOnCommand : public Command {
private:
    Light& light;
public:
    LightOnCommand(Light& light) : light(light) {}
    void execute() override {
        light.turnOn();
    }
};

// 具体命令类:关灯
class LightOffCommand : public Command {
private:
    Light& light;
public:
    LightOffCommand(Light& light) : light(light) {}
    void execute() override {
        light.turnOff();
    }
};

// 调用者类
class RemoteControl {
private:
    std::vector<std::unique_ptr<Command>> onCommands;
    std::vector<std::unique_ptr<Command>> offCommands;

public:
    void setCommand(size_t slot, std::unique_ptr<Command> onCmd, std::unique_ptr<Command> offCmd) {
        if (slot >= onCommands.size()) {
            onCommands.resize(slot + 1);
            offCommands.resize(slot + 1);
        }
        onCommands[slot] = std::move(onCmd);
        offCommands[slot] = std::move(offCmd);
    }

    void pressOnButton(size_t slot) {
        if (slot < onCommands.size() && onCommands[slot] != nullptr) {
            onCommands[slot]->execute();
        }
    }

    void pressOffButton(size_t slot) {
        if (slot < offCommands.size() && offCommands[slot] != nullptr) {
            offCommands[slot]->execute();
        }
    }
};

// 客户端代码
int main() {
    Light livingRoomLight;
    RemoteControl remote;
    remote.setCommand(0, std::make_unique_ptr<LightOnCommand>(livingRoomLight), std::make_unique_ptr<LightOffCommand>(livingRoomLight));
    remote.pressOnButton(0); // Light is on.
    remote.pressOffButton(0); // Light is off.
    return 0;
}
在这段代码中:

相关文章