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

命令模式把请求封装成对象,让发起者(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
构建调用者(Invoker)
调用者不关心命令细节,只负责存储并执行命令。支持历史记录和撤销时,用栈保存已执行命令:
class RemoteControl {
std::stack<:unique_ptr history std::unique_ptr current public: void setcommand cmd pressbutton if current- history.push undolast auto history.pop cmd- undo redo></:unique_ptr>组合使用示例
客户端代码简洁清晰,新增命令无需修改调用逻辑:
int main() {
Light livingRoomLight;
auto onCmd = std::make_unique<lightoncommand>(livingRoomLight);
auto offCmd = std::make_unique<lightoffcommand>(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(撤销上一次关灯)
}</lightoffcommand></lightoncommand>
基本上就这些。核心是分离“谁请求”和“谁干活”,命令对象本身承载上下文与行为,方便复用、组合和扩展。注意用智能指针管理生命周期,避免裸指针和资源泄漏。
C++免费学习笔记(深入):立即使用
在学习笔记中,你将探索 C++ 的入门与实战技巧!











