命令模式将操作封装为对象,实现请求与执行解耦。示例中通过Command接口、具体命令(如开灯、关灯)、接收者(灯)和调用者(遥控器)协作完成控制,支持扩展撤销、宏命令等功能,提升灵活性。

命令模式(Command Pattern)是一种行为设计模式,它将请求封装为对象,从而使你可以用不同的请求、队列或日志来参数化其他对象。在 C++ 中实现命令模式的关键是把“操作”变成一个可传递的对象,这样调用者不需要知道具体执行什么操作。
命令模式通常包含以下几个角色:
下面是一个简单的 C++ 示例,演示如何使用命令模式实现“开灯”和“关灯”操作。
#include <iostream>
#include <memory>
// 接收者:灯
class Light {
public:
void turnOn() {
std::cout << "灯打开了。\n";
}
void turnOff() {
std::cout << "灯关闭了。\n";
}
};
// 命令接口
class Command {
public:
virtual ~Command() = default;
virtual void execute() = 0;
};
// 具体命令:开灯
class LightOnCommand : public Command {
private:
Light& light;
public:
LightOnCommand(Light& l) : light(l) {}
void execute() override {
light.turnOn();
}
};
// 具体命令:关灯
class LightOffCommand : public Command {
private:
Light& light;
public:
LightOffCommand(Light& l) : light(l) {}
void execute() override {
light.turnOff();
}
};
// 调用者:遥控器
class RemoteControl {
private:
std::unique_ptr<Command> command;
public:
void setCommand(std::unique_ptr<Command> cmd) {
command = std::move(cmd);
}
void pressButton() {
if (command) {
command->execute();
}
}
};
在 main 函数中组合各个部分:
立即学习“C++免费学习笔记(深入)”;
int main() {
Light livingRoomLight; // 接收者
// 创建具体命令
auto onCommand = std::make_unique<LightOnCommand>(livingRoomLight);
auto offCommand = std::make_unique<LightOffCommand>(livingRoomLight);
RemoteControl remote; // 调用者
// 执行开灯
remote.setCommand(std::move(onCommand));
remote.pressButton();
// 执行关灯
remote.setCommand(std::make_unique<LightOffCommand>(livingRoomLight));
remote.pressButton();
return 0;
}
输出结果:
灯打开了。命令模式的优势在于解耦和扩展性。你可以轻松添加新命令而无需修改调用者代码。
例如,使用函数对象简化命令定义:
class FunctionCommand : public Command {
std::function<void()> action;
public:
FunctionCommand(std::function<void()> act) : action(std::move(act)) {}
void execute() override {
action();
}
};
然后可以直接传入 lambda 或函数:
remote.setCommand(std::make_unique<FunctionCommand>([&]() { std::cout << "自定义操作执行!\n"; }));基本上就这些。命令模式的核心思想是“把操作当作一等公民”,让程序更具弹性。C++ 中通过多态或函数包装都能很好地实现这一模式。
以上就是c++++怎么实现一个命令(Command)设计模式_c++命令模式(Command Pattern)实现的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号