自已的逻辑图
1.所谓命令模式就是将对象A所具有的Action分别抽象成command,即命令的对象化
例如:
对象灯泡有两个动作
turnOn
turnOff
2.为了让这两个action可以执行,也就是从灯泡分离开,我们创建一个抽象的类command
#ifndef COMMAND_H_
#define COMMAND_H_
class Command {
public:
Command();
virtual ~Command();
public:
virtual void execute()=0;
};
#endif /* COMMAND_H_ */
应注意的是该对象有个抽象的方法,execute
这个execute可以执行灯泡的方法,可能是
turnOn或者是turnOff,具体的就让他的实现类去实现
3.实现command
对象灯泡turnoff的command
/*
* FlipDownCommand.h
*
* Created on: 2015年10月27日
* Author: Administrator
*/
#ifndef FLIPDOWNCOMMAND_H_
#define FLIPDOWNCOMMAND_H_
#include "Command.h"
#include "Light.h"
class FlipDownCommand: public Command {
public:
FlipDownCommand(Light& light) :theLight(light){}
virtual void execute();
virtual ~FlipDownCommand();
private:
Light& theLight;
};
#endif /* FLIPDOWNCOMMAND_H_ */
对象灯泡turnon的command
/*
* FlipDownCommand.h
*
* Created on: 2015年10月27日
* Author: Administrator
*/
#ifndef FLIPDOWNCOMMAND_H_
#define FLIPDOWNCOMMAND_H_
#include "Command.h"
#include "Light.h"
class FlipDownCommand: public Command {
public:
FlipDownCommand(Light& light) :theLight(light){}
virtual void execute();
virtual ~FlipDownCommand();
private:
Light& theLight;
};
#endif /* FLIPDOWNCOMMAND_H_ */
这两个command的excute各自执行Light对应的turnoff和turnon方法
4.接着我们新建一个执行这两个命令的类
/*
* Switch.cpp
*
* Created on: 2015年10月27日
* Author: Administrator
*/
#include "Switch.h"
Switch::~Switch() {
// TODO Auto-generated destructor stub
}
void Switch::flipUp() {
flipUpCommand.execute();
}
void Switch::flipDown() {
flipDownCommand.execute();
}