大话设计模式13-命令模式-2020-9-24

1.命令模式简介

命令模式:将一个请求封装为一个对象,从而使得你可用不同的请求对客户进行参数化;对请求排队或者记录日志,以及支持可撤销的操作。UML类图如下:


2.实例

定义几个类模拟烧烤店烧烤场景,具体类图如下:
大话设计模式13-命令模式-2020-9-24_第1张图片
c++ 代码实现如下:

#include
#include 
#include
#include
using namespace std;
//13.命令模式:烧烤店烧烤
class Barbecuer
{
     
public:
	void bakeMutton()
	{
     
		cout << "烤羊肉串!" << endl;
	}
	void bakeChickenWing()
	{
     
		cout << "烤鸡翅!" << endl;
	}
};

class Command
{
     
public:
	Command(const string &istrName) :m_strName(istrName){
     }
	virtual ~Command(){
     };
	void setBarbecuer(Barbecuer iBarbecuer){
      m_barbecuer = iBarbecuer; }
	string getName(){
      return m_strName; }
	virtual void ExcuteCommand() = 0;
protected:
	string m_strName;
	Barbecuer m_barbecuer;
};

class BakeMuttonCommand:public Command
{
     
public:
	BakeMuttonCommand(const string &istrName) :Command(istrName){
     }
	void ExcuteCommand()override
	{
     
		m_barbecuer.bakeMutton();
	}
};

class BakeChickenWingCommand :public Command
{
     
public:
	BakeChickenWingCommand(const string &istrName) :Command(istrName){
     }
	void ExcuteCommand()override
	{
     
		m_barbecuer.bakeChickenWing();
	}
};

class Waiter
{
     
public:
	void addOrder(Command *ipCom)
	{
     
		m_commands.push_back(ipCom);
		cout << "新增订单:" << ipCom->getName() << endl;
	}
	void removeOrder(Command *ipCom)
	{
     
		for (auto itr = m_commands.begin(); itr != m_commands.end();++itr)
		{
     
			if (*itr==ipCom)
			{
     
				m_commands.erase(itr);
				cout << "移除订单:" << ipCom->getName() << endl;
				break;
			}
		}
	}
	void notify()
	{
     
		for (auto itr = m_commands.begin(); itr != m_commands.end(); ++itr)
		{
     
			(*itr)->ExcuteCommand();
		}
	}
private:
	list<Command*>m_commands;
};

int main()
{
     
	Barbecuer barbecuer;
	Command *pCom1 = new BakeMuttonCommand("烤羊肉串!");
	Command *pCom2 = new BakeChickenWingCommand("烤鸡翅!");
	Waiter girl;
	girl.addOrder(pCom1);
	girl.addOrder(pCom2);
	girl.notify();
	system("pause");
}

你可能感兴趣的:(大话设计模式,设计模式,c++)