命令模式將一個請求封裝爲一個對象,從而使你可用不同的請求對客戶進行參數化,對請求排隊或記錄請求日誌,以及支持可撤銷的操作。
命令模式的UML圖如下所示:
代碼如下:
class Barbecuer
{
public:
Barbecuer() {}
~Barbecuer() {}
void BakeMutton()
{
printf("Barbecuer yang rou\n");
}
void BakeChickenWing()
{
printf("Barbecuer ji chi\n");
}
};
class Command
{
protected:
Barbecuer *m_pReceive;
public:
Command(Barbecuer * __b ) : m_pReceive(__b)
{
}
virtual ~Command() {}
virtual void ExcuteCommand(){ }
virtual std::string CommandBehavior()
{
return "";
}
};
class BakeMuttonCommand : public Command
{
public:
BakeMuttonCommand(Barbecuer * __b) : Command(__b)
{
}
~BakeMuttonCommand() {}
virtual void ExcuteCommand()
{
m_pReceive->BakeMutton();
}
virtual std::string CommandBehavior()
{
return "BakeMuttonCommand";
}
};
class BakeChickenWingCommand : public Command
{
public:
BakeChickenWingCommand(Barbecuer * __b) : Command(__b)
{
}
~BakeChickenWingCommand() {}
virtual void ExcuteCommand()
{
m_pReceive->BakeChickenWing();
}
virtual std::string CommandBehavior()
{
return "BakeChickenWingCommand";
}
};
string getTime()
{
time_t timep;
time(&timep);
char tmp[64];
strftime(tmp, sizeof(tmp), "%Y-%m-%d %H:%M:%S", localtime(&timep));
return tmp;
}
class Waiter
{
private:
list<Command*> m_coms;
public:
Waiter() {}
~Waiter()
{
for each (Command* pCom in m_coms)
{
if (pCom)
{
delete pCom;
pCom = NULL ;
}
}
}
void SetOrder(Command* __c)
{
if (NULL == __c)
{
cout << "Have not something to eat" << endl;
}
else
{
m_coms.push_back(__c);
cout << "Add order:" <<__c->CommandBehavior() << " Current Time:" << getTime()<<endl;
}
}
void CancelOrder(Command* __c)
{
m_coms.remove(__c);
cout << "Cancel order:" << __c->CommandBehavior() << " Current Time:" << getTime()<<endl;
}
void Notify()
{
for each (Command* pCom in m_coms)
{
pCom->ExcuteCommand();
}
}
};
//客戶端代碼
int _tmain(int argc, TCHAR* argv[])
{
Barbecuer *__b = new Barbecuer() ;
Command * pCom1 = new BakeMuttonCommand(__b);
Command * pCom2 = new BakeMuttonCommand(__b);
Command * pCom3 = new BakeChickenWingCommand(__b);
Waiter *pWaiter = new Waiter();
pWaiter->SetOrder(pCom1);
pWaiter->SetOrder(pCom2);
pWaiter->SetOrder(pCom3);
pWaiter->SetOrder(NULL);
pWaiter->Notify();
cout << "=============" << endl;
pWaiter->CancelOrder(pCom2);
pWaiter->Notify();
if (__b)
{
delete __b;
__b = NULL;
}
if (pWaiter)
{
delete pWaiter;
pWaiter = NULL;
}
return 0;
}
運行結果: