命令模式
定义
将请求封装成对象,以便使用不同的请求、队列或者日志来参数化其他对象。命令模式支持可撤销操作。
类图
代码示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
| class Light { public: void on() { cout << "Light on!" << endl; }
void off() { cout << "light off!" << endl; } };
class Door { public: void open() { cout << "Door open!" << endl; }
void close() { cout << "Door close!" << endl; } };
class Command { public: virtual void execute() = 0; virtual void undo() = 0; };
class LightOnCommand :public Command { public: LightOnCommand(Light* li) :light(li) {
}
void execute() { light->on(); }
void undo() { light->off(); } private: Light* light; };
class LightOffCommand :public Command { public: LightOffCommand(Light* li) :light(li) {
}
void execute() { light->off(); }
void undo() { light->on(); } private: Light* light; };
class DoorOpenCommand :public Command { public: DoorOpenCommand(Door* doo) :door(doo) {
}
void execute() { door->open(); }
void undo() { door->close(); } private: Door* door;
};
class DoorCloseCommand :public Command { public: DoorCloseCommand(Door* doo) :door(doo) {
}
void execute() { door->close(); }
void undo() { door->open(); } private: Door* door;
};
class RemoteControl { private: Command* onCommand; Command* offCommand; public: RemoteControl() :onCommand(nullptr), offCommand(nullptr) {
}
void setCommand(Command* onCommand, Command* offCommand) { this->offCommand = offCommand; this->onCommand = onCommand; }
void onButtonPushed() { if (onCommand) { onCommand->execute(); } }
void offButtonPushed() { if (offCommand) { offCommand->execute(); } } };
|
理解
利用command接口,每个动作都继承这个接口成为一个命令对象,命令对象持有一个执行命令的实体,当该动作执行时,命令对象直接调用执行者的对应动作。有利于动作扩展,新动作只要继承command接口就行。