命令模式:将一个请求封装为一个对象,从而使你可用不同的请求客户进行参数化;对请求排队或记录请求日志,以及支持可撤销的操作。
命令模式就是一个请求接口,将一个操作的对象和对象的执行分割开。互不干涉。较为容易的实现命令的队列,记入日志和请求的撤销和重做等一些操作。
一个简单的命令模式的说明代码:
#include<iostream>
using namespace std;
class Receiver;
class Command
{
protected:
Receiver* receiver;
public:
Command(Receiver* receiver)
{
this->receiver = receiver;
}
virtual void Execute() = 0;
};
class ConcreteCommand : public Command
{
public:
ConcreteCommand(Receiver* receiver):Command(receiver){}
void Execute();
};
class Invoker
{
private:
Command* command;
public:
void SetCommand(Command* command)
{
this->command = command;
}
void ExecuteCommand()
{
command->Execute();
}
};
class Receiver
{
public:
void Action()
{
cout << "请求执行" << endl;
}
};
void ConcreteCommand::Execute()
{
receiver->Action();
}
int main()
{
Receiver* r = new Receiver();
Command* c = new ConcreteCommand(r);
Invoker* i = new Invoker();
i->SetCommand(c);
i->ExecuteCommand();
return 0;
}
通过阅读《大话设计模式》,增加一个实例的命令模式来详细的解释说明:
#include <iostream>
#include <string>
#include <list>
using namespace std;
/*烤肉类*/
class Barbecuer
{
public:
void BakeMutton(){cout<<"Bake mutton"<<endl;}
void BakeChickenWing(){cout<<"Bake ChickenWing"<<endl;}
};
/*抽象命令类:是执行具体操作的接口*/
class Command
{
public:
Command(){}
Command(Barbecuer *receiver):m_receiver(receiver){}
virtual void ExecuteCommand() = 0; //执行命令
protected:
Barbecuer *m_receiver;
};
/*烤羊肉串命令*/
class BakeMuttonCommand:public Command
{
public:
BakeMuttonCommand(Barbecuer *receiver){m_receiver = receiver;}
void ExecuteCommand(){m_receiver->BakeMutton();}
};
/*烤鸡翅串命令*/
class BakeChickenWingCommand:public Command
{
public:
BakeChickenWingCommand(Barbecuer *receiver){m_receiver = receiver;}
void ExecuteCommand()
{m_receiver->BakeChickenWing();}
};
/*服务员类*/
class Waiter
{
public:
void SetOrder(Command *command);
void Notify();
private:
list<Command *>m_commandList; //这里相当于一个命令对象队列
};
void Waiter::SetOrder(Command *command)
{
m_commandList.push_back(command);
cout << "增加烤肉命令" << endl;
}
void Waiter::Notify()
{
list<Command*>::iterator i;
for(i = m_commandList.begin(); i != m_commandList.end(); ++ i)
(*i)->ExecuteCommand();
}
int main()
{
//生成烤肉、服务员、订单对象
Barbecuer* m_cook = new Barbecuer();
Command* m_mutton = new BakeMuttonCommand(m_cook);
Command* m_chickenwing = new BakeChickenWingCommand(m_cook);
Waiter* m_waiter = new Waiter();
//将订单对象送到命令队列
m_waiter->SetOrder(m_mutton);
m_waiter->SetOrder(m_chickenwing);
//服务员通知烤肉具体订单
m_waiter->Notify();
delete m_cook;
m_cook = NULL;
delete m_mutton;
m_mutton = NULL;
delete m_chickenwing;
m_chickenwing = NULL;
delete m_waiter;
m_waiter = NULL;
return 0;
}