声明:本博文篇幅短,适合review。
一、概念
将一个请求封装为一个对象,从而可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可取消的操作。
二、模式结构图
class Command
{
public:
virtual ~Command();
virtual void excute() = 0;
};
class ConcreteCommand : public Command
{
public:
ConcreteCommand(Receiver * rcv) {
mRcv = rcv;
}
void excute(){
mRcv->action();
}
private:
Receiver * mRcv;
};
class Invoker
{
public:
void addCommand(Command * cd){
mVec.push_back(cd);
}
void excuteCommand(){
vector<Command *>::iterator it = mVec.begin();
for (; it != mVec.end(); it++){
(*it)->excute();
}
}
private:
vector<Command *> mVec;
};
class Receiver
{
public:
void action(){
cout<<"do action"<<endl;
}
};
void main()
{
Receiver * r = new Receiver();
Command * c1 = new ConcreteCommand(r);
Command * c2 = new ConcreteCommand(r);
Invoker * i = new Invoker();
i->addCommand(c1);
i->addCommand(c2);
i.excuteCommand();
}
三、例子
class Order
{
public:
virtual ~Order();
virtual void excute() = 0;
};
class DrinkOrder : public Order
{
public:
DrinkOrder(Cooker * ck) {
mCk = ck;
}
void excute(){
mCk->makeDrink();
}
private:
Cooker * mCk;
};
class FoodOrder : public Order
{
public:
FoodOrder(Cooker * ck) {
mCk = ck;
}
void excute(){
mCk->makeFood();
}
private:
Cooker * mCk;
}
class Waitor
{
public:
void addOrder(Order * rd){
mVec.push_back(rd);
}
void removeOrder(){
}
void excuteOrder(){
vector<Order *>::iterator it = mVec.begin();
for (; it != mVec.end(); it++){
(*it)->excute();
}
}
private:
vector<Order *> mVec;
};
class Cooker
{
public:
void makeDrink(){
cout<<"make drink"<<endl;
}
void makeFood(){
cout<<"make food"<<endl;
}
};
void main()
{
Cooker * ck = new Cooker();
Order * d = new DrinkOrder(ck);
Order * f = new FoodOrder(ck);
Waitor * w = new Waitor();
w->addOrder(d);
w->addOrder(f);
w.excuteOrder();
}
四、优缺点
1、优点
a、降低了系统的耦合度
b、满足开闭原则
c、可以容易地实现对请求的Undo和Redo
2、缺点
a、使用命令模式可能会导致某些系统有过多的具体命令类