您的位置:首页 > 其它

设计模式-命令模式

2015-09-17 16:09 459 查看
命令模式:把命令、请求封装成对象,以便使用不同的请求队列或日志来参数化其他对象。命令模式也支持可撤销的操作。简单的来说就是把对象之间的通信行为封装成类的模式,封装后可以把发出命令的对象和执行命令的对象解耦。并且把命令实例化后可以撤销,延时,排序等操作。

讨论模型:蝙蝠侠(BatMan)是控制者(controller),他对灯发出命令(command)控制灯的亮和灭;

灯Light类:

#ifndef __________Light_h
#define __________Light_h
#include <iostream>
class Light{
public:
void LightOn(){
printf("Light On\n");//调用该方法将等打开
}
void LightOff(){
printf("Light Off\n");//熄灭
}
};

#endif


command基类:

#ifndef __________command_h
#define __________command_h

class command {
public:
virtual void execute()=0;//执行函数
};
#endif


继承自command的LightOnCommand

#ifndef __________LightOnCommand_h
#define __________LightOnCommand_h
#include "command.h"
#include "Light.h"
class LightOnCommand : public command   {
public:
Light* _light;
public:
LightOnCommand(Light* light){
_light = light;
}
void execute(){
_light ->LightOn();
}
};

#endif


LightOffCommand:

#ifndef __________LightOffCommand_h
#define __________LightOffCommand_h
#include <iostream>
#include "command.h"
#include "Light.h"
class LightOffCommand : public command{
public:
Light* _light;
public:
LightOffCommand(Light* light){
_light = light;
}
void execute(){
_light->LightOff();
}
};

#endif


控制者controller:

#ifndef __________controller_h
#define __________controller_h
#include "command.h"
class controller{
public:
command* _command;//命令对象
public:
void setCommand(command* command){
_command = command;//保存命令对象
}
void control(){
_command->execute();//执行命令对象的execute方法
}

};

#endif


#include <iostream>
#include "Light.h"
#include "LightOnCommand.h"
#include "LightOffCommand.h"
#include "controller.h"

int main(int argc, const char * argv[]) {
auto BatMan = new controller();//控制者
auto light = new Light();//执行者
command* command = new LightOnCommand(light);//命令
BatMan->setCommand(command);//设置控制者将要执行的命令
BatMan->control();//控制者发出指令让执行者执行

command = new LightOffCommand(light);
BatMan->setCommand(command);
BatMan->control();
return 0;
}


输出:Light On

Light Off

从上的例子可以看出命令模式把以前的控制者->执行者模式改为控制者->命令->执行者。把命令实例化,这样可以把命令储存起来,甚至可以做排序、撤销等操作。并可以实现执行与控制的解耦,是面对接口编程的思想。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  设计模式