C++如何实现一个命令模式(Command Pattern)?(设计模式)


命令模式通过将请求封装为对象实现发起者与执行者解耦,支持撤销、排队等功能;C++中以抽象基类Command定义execute()和undo()接口,具体命令类继承并实现。

C++如何实现一个命令模式(Command Pattern)?(设计模式)

命令模式把请求封装成对象,让发起者(Invoker)和执行者(Receiver)解耦,支持撤销、排队、日志、事务等扩展。C++中通过抽象基类定义命令接口,用具体类实现不同操作,再由调用者统一触发。

定义命令接口

用抽象类 Command 声明 execute() 和可选的 undo() 方法,所有具体命令都继承它:

class Command { public:     virtual ~Command() = default;     virtual void execute() = 0;     virtual void undo() { } // 默认空实现,按需重写 };

实现具体命令

每个命令封装一个接收者(Receiver)和对应动作。比如控制灯的开关:

class Light { public:     void on()  { std::cout << "Light is ONn"; }     void off() { std::cout << "Light is OFFn"; } };  class LightOnCommand : public Command {     Light& light; public:     explicit LightOnCommand(Light& l) : light(l) {}     void execute() override { light.on(); }     void undo() override { light.off(); } };  class LightOffCommand : public Command {     Light& light; public:     explicit LightOffCommand(Light& l) : light(l) {}     void execute() override { light.off(); }     void undo() override { light.on(); } }

构建调用者(Invoker)

调用者不关心命令细节,只负责存储并执行命令。支持历史记录和撤销时,用栈保存已执行命令:

立即学习C++免费学习笔记(深入)”;

class RemoteControl {     std::stack> history;     std::unique_ptr current;  public:     void setCommand(std::unique_ptr cmd) {         current = std::move(cmd);     }      void pressButton() {         if (current) {             current->execute();             history.push(std::move(current));         }     }      void undoLast() {         if (!history.empty()) {             auto cmd = std::move(history.top());             history.pop();             cmd->undo();             current = std::move(cmd); // 便于再次 undo 或 redo(如需)         }     } };

组合使用示例

客户端代码简洁清晰,新增命令无需修改调用逻辑:

int main() {     Light livingRoomLight;          auto onCmd = std::make_unique(livingRoomLight);     auto offCmd = std::make_unique(livingRoomLight);      RemoteControl remote;     remote.setCommand(std::move(onCmd));     remote.pressButton(); // Light is ON      remote.setCommand(std::move(offCmd));     remote.pressButton(); // Light is OFF      remote.undoLast(); // Light is ON(撤销上一次关灯) }

基本上就这些。核心是分离“谁请求”和“谁干活”,命令对象本身承载上下文与行为,方便复用、组合和扩展。注意用智能指针管理生命周期,避免裸指针和资源泄漏。