C++:設計模式之命令模式(例子)
阿新 • • 發佈:2019-02-09
// 設計模式測試.cpp : 定義控制檯應用程式的入口點。 // 命令模式 #include "stdafx.h" #include <string> #include <iostream> #include <vector> #include <list> using namespace std; /*********************命令模式_遙控器示例*************************************/ //燈類 class Light { public: void on() { cout << "Light On!" << endl; } }; //門類 class Door { public: void open() { cout << "Door Open!" << endl; } }; //命令介面 class ICommand { public: virtual void execute() = 0; }; class LightOnCommand: public ICommand { public: Light *light; LightOnCommand(Light *light) { this->light = light; } virtual void execute() { light->on(); } }; class DoorOpenCommand : public ICommand { public: Door *door; DoorOpenCommand(Door *door) { this->door = door; } virtual void execute() { door->open(); } }; //遙控器 class SimpleRemoteControl { public: ICommand *slot; void setCommand(ICommand *command) { slot = command; } void buttonWasPressed() { slot->execute(); } }; //主函式 int main() { SimpleRemoteControl *remote = new SimpleRemoteControl(); Light *light = new Light(); Door *door = new Door(); LightOnCommand *lightOn = new LightOnCommand(light); DoorOpenCommand *doorOpen = new DoorOpenCommand(door); remote->setCommand(lightOn); remote->buttonWasPressed(); remote->setCommand(doorOpen); remote->buttonWasPressed(); system("Pause"); return 0; }