DesignPatterns/c++/command.cc
2025-07-10 22:26:33 +08:00

36 lines
642 B
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* @name 命令模式
* @brief: 将请求封装为对象
* @note 场景GUI 按钮操作、撤销/重做功能、任务队列
*/
class Command {
public:
virtual void execute() = 0;
};
class Light {
public:
void turnOn() {}
};
class LightOnCommand : public Command {
Light* light;
public:
void execute() override { light->turnOn(); }
};
class RemoteControl {
Command* command;
public:
void setCommand(Command* cmd) { command = cmd; }
void pressButton() { command->execute(); }
};
// 使用
int main()
{
RemoteControl remote;
remote.setCommand(new LightOnCommand());
remote.pressButton();
}