36 lines
642 B
C++
36 lines
642 B
C++
/**
|
||
* @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();
|
||
} |