## 模式定義:
? ? ? 命令模式將“請求”封裝成對象,以便使用不同的請求、隊列或者日志來參數化其他對象。命令模式也支持可撤銷的操作。
? ? ? 命令對象將動作和接受者包進對象中,這個對象只暴露一個execute()方法。
? ? ? 當需要將發出請求的對象和執行請求的對象解耦的時候,使用命令模式。
## 模式結構:

## 舉例:
? ? ? 遙控器上有一個插槽,可以放上不同的裝置,然后用按鈕控制。我們這里放置電燈,并有開和關按鈕。可以命令模式實現。
## UML設計:

? ? ? 其中,RemoteControl為遙控器,LightOnCommand為開燈請求對象,LightOffCommand為關燈請求對象,他們繼承自基類Command,這樣設計可以使插槽在以后防止其他的裝置。
## 編程實現及執行結果:
~~~
#include <iostream>
using namespace std;
//電燈類
class Light
{
public:
void on()
{
cout << "Light on !" << endl;
}
void off()
{
cout << "Light off !" << endl;
}
};
//命令類
class Command
{
public:
virtual void execute(){}
};
//具體命令類
class LigthOnCommand : public Command
{
public:
LigthOnCommand(Light* lig):light(lig){}
//execute方法
void execute()
{
light->on();
}
private:
Light* light;
};
class LigthOffCommand : public Command
{
public:
LigthOffCommand(Light* lig):light(lig){}
void execute()
{
light->off();
}
private:
Light* light;
};
//遙控器類
class RemoteControl
{
public:
void setCommand(Command* command)
{
slot = command;
}
void buttonOn()
{
slot->execute();
}
private:
Command* slot;
};
//客戶代碼
int main()
{
RemoteControl lightOnControl;
RemoteControl lightOffControl;
Command* onCommand = new LigthOnCommand(new Light());
Command* offCommand = new LigthOffCommand(new Light());
lightOnControl.setCommand(onCommand);
lightOffControl.setCommand(offCommand);
lightOnControl.buttonOn();
lightOffControl.buttonOn();
return 0;
}
~~~
執行結果:
**Lighton !**
**Lightoff !**
**請按任意鍵繼續. . .**