大话设计模式命令模式c++实现

命令模式

其他二十三种设计模式

#include<iostream>
#include<queue>

using namespace std;
//命令模式
//Receiver类
class Barbecuer {
    
    
public:
	void BakeMutton() {
    
    
		cout << "烤羊肉串!" << endl;
	}
	void BakeChickWing() {
    
    
		cout << "烤鸡翅!" << endl;
	}
};

//抽象命令类
class AbstractCommand {
    
    
public:
	AbstractCommand(Barbecuer* _receiver) {
    
    
		this->receiver = _receiver;
	}

	virtual void ExcuteCommand() = 0;

protected:
	Barbecuer* receiver;
};

//具体命令类
class BakeMuttonCommand :public AbstractCommand {
    
    
public:
	BakeMuttonCommand(Barbecuer* _receiver) :AbstractCommand(_receiver) {
    
    }
	virtual void ExcuteCommand() {
    
    
		receiver->BakeMutton();
	}
};

class BakeChickWingCommand :public AbstractCommand {
    
    
public:
	BakeChickWingCommand(Barbecuer* _receiver) :AbstractCommand(_receiver) {
    
    }
	virtual void ExcuteCommand() {
    
    
		receiver->BakeMutton();
	}
};

//Invoker类
class Waiter {
    
    
public:
	void SetOrder(AbstractCommand* _command) {
    
    
		if (typeid(*_command)== typeid(BakeChickWingCommand))
		{
    
    
			cout << "服务员:鸡翅没有了,请点别的烧烤。" << endl;
		}
		else
		{
    
    
			command.push(_command);
			cout << "增加订单: 烤羊肉" << endl;
		}
	}
	void CancelOrder(AbstractCommand* _command) {
    
    
		if (!command.empty())
		{
    
    
			for (unsigned int i = 0; i <= (unsigned int)command.size(); ++i) {
    
    
				if (command.front() == _command) {
    
    
					command.pop();
					cout << "取消订单:" << "烤羊肉" << endl;
					//"烤羊肉"是直接cout,有点问题					
				}
				else {
    
    
					AbstractCommand* pcommand = command.front();
					command.pop();
					command.push(pcommand);
				}
			}
		}
	}
	void Notify() {
    
    
		for (unsigned int i = 0; i <= (unsigned int)command.size(); ++i) {
    
    
			AbstractCommand* valueCommand = command.front();
			valueCommand->ExcuteCommand();
			command.pop();
		}
	}

protected:
	BakeChickWingCommand* pBakeChickWing = NULL;
	BakeMuttonCommand* pBakeMuttonCommand=NULL;

private:
	queue<AbstractCommand*> command;
};

void test1() {
    
    
	Barbecuer* boy = new Barbecuer();
	AbstractCommand* BakeMuttonCommand1 = new BakeMuttonCommand(boy);
	AbstractCommand* BakeMuttonCommand2 = new BakeMuttonCommand(boy);
	AbstractCommand* BakeChickWingCommand1 = new BakeChickWingCommand(boy);
	Waiter* girl = new Waiter();

	girl->SetOrder(BakeMuttonCommand1);
	girl->SetOrder(BakeMuttonCommand2);
	girl->SetOrder(BakeChickWingCommand1);
	girl->CancelOrder(BakeMuttonCommand1);

	girl->Notify();
}

int main() {
    
    
	test1();
	return 0;
}

猜你喜欢

转载自blog.csdn.net/wode_0828/article/details/114163376