目录
1. 例子-创建一组控制遥控器的API
2. 定义命令模式
命令模式其实就是定义一个命令接口,然后具体命令实现这个接口,只暴露出命令的接口
命令模式:将“请求”封装成对象,以便使用不同的请求、队列或者日志来参数化其他对象。命令模式也支持可撤销操作。
3. 命令模式的更多用途
3.1 队列请求
3.2 日志请求
4. 部分源码
4.1 Command.h
class Command{
public:
std::string name="Command";
virtual void execute()=0;
virtual void undo()=0;
virtual ~Command(){};
};
4.2 CeilingFan.h
enum{OFF,LOW,MEDIUM,HIGH};
class CeilingFan{
public:
string location;
int speed;
CeilingFan(string location);
void high();
void medium();
void low();
void off();
int getSpeed();
};
4.3 CeilingFanHighCommand.h
#include "Command.h"
#include "CeilingFan.h"
class CeilingFanHighCommand:public Command{
public:
CeilingFanHighCommand(CeilingFan *ceilingFan);
virtual void execute()override final;
virtual void undo()override final;
virtual ~CeilingFanHighCommand();
private:
CeilingFan *ceilingFan;
int prevSpeed;
};
4.4 CeilingFanHighCommand.cpp
#include "CeilingFanHighCommand.h"
CeilingFanHighCommand::CeilingFanHighCommand(CeilingFan *ceilingFan)
{
name="CeilingFanHighCommand";
this->ceilingFan=ceilingFan;
}
void CeilingFanHighCommand::execute()
{
prevSpeed=ceilingFan->getSpeed();
ceilingFan->high();
}
void CeilingFanHighCommand::undo()
{
if (prevSpeed == HIGH) {
ceilingFan->high();
} else if (prevSpeed == MEDIUM) {
ceilingFan->medium();
} else if (prevSpeed == LOW) {
ceilingFan->low();
} else if (prevSpeed == OFF) {
ceilingFan->off();
}
}
CeilingFanHighCommand::~CeilingFanHighCommand()
{
}
5. 总结
命令模式将发出请求的对象和执行请求的对象解耦