命令模式:将一个请求封装一个对象,从而使你可用不同的请求对客户进行参数化,对请求排队或记录请求日志,以及支持课撤销的操作
一个例子:烧烤厨师,各户的要求,服务员
代码如下:
//烧烤厨师
#ifndef BARBECUER_H #define BARBECUER_H #include <iostream> using std::cout; using std::endl; class Barbecuer { public: void BakeMutton()const { cout<<"烤羊肉串 "; } void BakeChickenWing()const { cout<<"烤鸡翅" ; } }; #endif
//Command
#ifndef COMMAND_H #define COMMAND_H #include <iostream> #include <string> #include "Barbecuer.h" using std::cout; using std::endl; using std::string; class Command { public: Command(Barbecuer* b=0,int nu=0):bar(b),num(nu){} virtual ~Command(){} public: virtual void ExcuteCommand()=0; void SetBarName(string name){BarName=name;} string GetBarName()const{return BarName;} int GetNum()const{return num;} protected: Barbecuer* bar; string BarName; int num; }; #endif
//烧烤羊肉的要求
#include "Command.h" class BakeMuttonCommand:public Command { public: BakeMuttonCommand(Barbecuer* b=0,int nu=0):Command(b,nu){SetBarName("烤羊肉串");} ~BakeMuttonCommand(){} public: virtual void ExcuteCommand() { bar->BakeMutton(); cout<<num<<"个"<<endl; } }; //烧烤鸡翅的要求与之类似
//服务员类
//Waiter.h #pragma once class Command; #include <vector> using std::vector; class Waiter { public: Waiter(void); ~Waiter(void); public: void SetOrder(Command* command); void CancerOrder(Command* command); void Notify(); void Refresh(); private: vector<Command*> vecCommands; }; //Waiter.cpp #include "Waiter.h" #include "Command.h" #include <algorithm> Waiter::Waiter(void) { } Waiter::~Waiter(void) { } void Waiter::SetOrder(Command* command) { vecCommands.push_back (command); cout<<"需要:"<<command->GetBarName() <<","<<command->GetNum ()<<"个/n"; } void Waiter::CancerOrder(Command* command) { vector<Command*>::iterator iter; iter=find(vecCommands.begin (),vecCommands.end (),command); Command* com=0; if(iter!=vecCommands.end ()) { com=*iter; vecCommands.erase (iter); cout<<"取消:"<<command->GetBarName() <<","<<command->GetNum ()<<"个/n"; delete com; } } void Waiter::Notify() { vector<Command*>::iterator iter=vecCommands.begin (); while(iter!=vecCommands.end ()) { (*iter)->ExcuteCommand (); ++iter; } Refresh(); } void Waiter::Refresh() { vector<Command*>::iterator iter=vecCommands.begin (); while(iter!=vecCommands.end ()) { delete *(iter++); } vecCommands.erase (vecCommands.begin (),vecCommands.end ()); }
//主程序
#include "Waiter.h" #include "BakeChickenWingCommand.h" #include "BakeMuttonCommand.h" int main() { Waiter girl; Barbecuer* bar=new Barbecuer(); Command* MuttonCommand1=new BakeChickenWingCommand(bar,10); Command* ChickenWingCommand2=new BakeChickenWingCommand(bar,4); girl.SetOrder (MuttonCommand1); girl.SetOrder (ChickenWingCommand2); girl.CancerOrder (MuttonCommand1); girl.Notify (); delete bar; return 0; } 结果: 需要:烤鸡翅,10个 需要:烤鸡翅,4个 取消:烤鸡翅,10个 烤羊肉串 4个