提交 1f469a66 编写于 作者: L liu-jianhao

Command-Pattern Head-First版

上级 46e47237
#ifndef COMMAND_HPP
#define COMMAND_HPP
class Command {
public:
virtual void execute() = 0;
virtual ~Command() = default;
};
#endif
\ No newline at end of file
#ifndef GARAGEDOOROPEN_HPP
#define GARAGEDOOROPEN_HPP
#include <string>
#include <iostream>
#include "Command.hpp"
class GarageDoorOpen : public Command {
private:
std::string door;
public:
GarageDoorOpen(std::string g) : door(g) {}
void execute() {
std::cout << door << " was opened" << std::endl;
}
};
#endif
\ No newline at end of file
#ifndef LIGHTONCOMMAND_HPP
#define LIGHTONCOMMAND_HPP
#include <string>
#include <iostream>
#include "Command.hpp"
class LightOnCommand : public Command {
private:
std::string light;
public:
LightOnCommand(std::string l) : light(l) {}
void execute() {
std::cout << light << " was turned on" << std::endl;
}
};
#endif
\ No newline at end of file
all:
g++ -g -Wall main.cpp -o main
clean:
rm main
## 命令模式
![](https://img-blog.csdnimg.cn/20190616212348873.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlc3Ricm9va2xpdQ==,size_16,color_FFFFFF,t_70)
\ No newline at end of file
#ifndef SIMPLEREMOTECONTROL_HPP
#define SIMPLEREMOTECONTROL_HPP
#include "Command.hpp"
class SimpleRemoteControl {
private:
Command *slot;
public:
void setCommand(Command *command) {
slot = command;
}
void buttonWasPressed() {
slot->execute();
}
};
#endif
\ No newline at end of file
#include "LightOnCommand.hpp"
#include "SimpleRemoteControl.hpp"
#include "GarageDoorOpen.hpp"
int main() {
SimpleRemoteControl *remote = new SimpleRemoteControl();
LightOnCommand *lightOn = new LightOnCommand("my light");
remote->setCommand(lightOn);
remote->buttonWasPressed();
GarageDoorOpen *doorOpen = new GarageDoorOpen("my garage door");
remote->setCommand(doorOpen);
remote->buttonWasPressed();
delete remote;
delete lightOn;
delete doorOpen;
}
\ No newline at end of file
......@@ -71,6 +71,7 @@
+ [Chain of Resposibility(职责链)](https://github.com/liu-jianhao/Cpp-Design-Patterns/tree/master/Chain%20of%20Resposibility)
### 行为变化:
+ [Command](https://github.com/liu-jianhao/Cpp-Design-Patterns/tree/master/Command)
+ [Command(Head-First版)](https://github.com/liu-jianhao/Cpp-Design-Patterns/tree/master/Command-Pattern)
+ [Visitor](https://github.com/liu-jianhao/Cpp-Design-Patterns/tree/master/Visitor)
### 领域问题:
+ [Interpreter](https://github.com/liu-jianhao/Cpp-Design-Patterns/tree/master/Interpreter)
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册