命令模式(Command)的目標(biāo)是將一個請求封裝成一個對象,因此可以參數(shù)化多個客戶的不同請求,將請求排除,記錄請求日志,并支持撤消操作。 結(jié)構(gòu)圖如下:

其實現(xiàn)思想是將一個請求封裝到一個類中(Command),再提供接收對象(Receiver),最后Command命令由Invoker調(diào)用。
以一個電燈開關(guān)為例,命令的執(zhí)行、不執(zhí)行相對于開關(guān)的打開、關(guān)閉操作,由開關(guān)發(fā)出命令,電燈接收命令,結(jié)構(gòu)圖如下:

實現(xiàn)代碼:
//Light.h
class Light
{
public:
Light();
virtual ~Light();
void TurnOn();
void TurnOff();
};
//Light.cpp
#include "stdafx.h"
#include "Light.h"
#include <iostream>
using namespace std;
Light::Light()
{
}
Light::~Light()
{
}
void Light::TurnOn()
{
cout << "電燈打開了" << endl;
}
void Light::TurnOff()
{
cout << "電燈關(guān)閉了" << endl;
}
//Command.h
class Command
{
public:
virtual ~Command();
virtual void Execute() = 0;
virtual void UnExecute() = 0;
protected:
Command();
};
//Command.cpp
#include "stdafx.h"
#include "Command.h"
Command::Command()
{
}
Command::~Command()
{
}
//LightCommand.h
#include "Command.h"
class Light;
class LightCommand : public Command
{
public:
LightCommand(Light*);
virtual ~LightCommand();
void Execute();
void UnExecute();
private:
Light* m_pLight;
};
//LightCommand.cpp
#include "stdafx.h"
#include "LightCommand.h"
#include "Light.h"
LightCommand::LightCommand(Light* pLight)
{
m_pLight = pLight;
}
LightCommand::~LightCommand()
{
if(m_pLight != NULL)
{
delete m_pLight;
m_pLight = NULL;
}
}
void LightCommand::Execute()
{
m_pLight->TurnOn();
}
void LightCommand::UnExecute()
{
m_pLight->TurnOff();
}
//Switch.h
class Command;
class Switch
{
public:
Switch(Command*);
virtual ~Switch();
void Open();
void Close();
private:
Command* m_pCommand;
};
//Switch.cpp
#include "stdafx.h"
#include "Switch.h"
#include "Command.h"
Switch::Switch(Command* pCommand)
{
m_pCommand = pCommand;
}
Switch::~Switch()
{
}
void Switch::Open()
{
m_pCommand->Execute();
}
void Switch::Close()
{
m_pCommand->UnExecute();
}
//main.cpp
#include "stdafx.h"
#include "Switch.h"
#include "Light.h"
#include "LightCommand.h"
int main(int argc, char* argv[])
{
Light* pLight = new Light;
Command* pCommand = new LightCommand(pLight);
Switch* pSwitch = new Switch(pCommand);
pSwitch->Open();
pSwitch->Close();
return 0;
}
最后輸出為:
電燈打開了
電燈關(guān)閉了