学习笔记:命令模式
模式简介
:属于行为型模式,请求以命令的形式包裹在对象中,并传给调用对象。
为什么用
:请求发出者和实现者往往是一种直接调用的关系,这样导致在处理撤销,记录行为方面难以处理,把命令包装成对象方便解耦。
怎么样用
:把对象的方法写成对象,实现一个共同的接口,然后写个类管理所有的命令。
注意事项
:命令可能有点多。
实际举例
:人物移动命令实现。
#include<iostream>
#include <vector>
using namespace std;
class Order {
public:
virtual void execute() {
cout << "待实现的方法";
};
};
class Move {
public:
enum class Direction {
Up,
Down,
Left,
Right
};
void doUp() {
cout << "人物向上走\n";
}
void doDown() {
cout << "人物向下走\n";
}
void doLeft() {
cout << "人物向左走\n";
}
void doRight() {
cout << "人物向右走\n";
}
};
class Move_Up :public Order {
private:
Move* move;
public:
Move_Up(Move* _move) {
this->move = _move;
}
void execute() {
move->doUp();
}
};
class Move_Down :public Order {
private:
Move* move;
public:
Move_Down(Move* _move) {
this->move = _move;
}
void execute() {
move->doDown();
}
};
class Move_Left :public Order {
private:
Move* move;
public:
Move_Left(Move* _move) {
this->move = _move;
}
void execute() {
move->doLeft();
}
};
class Move_Right :public Order {
private:
Move* move;
public:
Move_Right(Move* _move) {
this->move = _move;
}
void execute() {
move->doRight();
}
};
class OrderCollection {
private:
vector<Order*>v;
public:
void takeOrder(Order *order) {
v.push_back(order);
}
void placeOrder() {
int size = v.size();
for (int i = 0; i < size; ++i) {
cout << "第" << i+1 << "条命令: ";
v[i]->execute();
}
v.clear();
}
};
int main()
{
OrderCollection orderCollection;
Move* move = new Move();
orderCollection.takeOrder(new Move_Up(move));
orderCollection.takeOrder(new Move_Down(move));
orderCollection.takeOrder(new Move_Left(move));
orderCollection.takeOrder(new Move_Right(move));
orderCollection.placeOrder();
return 0;
}