设计模式 --命令模式

#include<iostream>
#include<queue>
#include<Windows.h>
using namespace std;

//命令模式  
//将一个请求封装成为一个对象,从而让我们可用不同的请求对客户进行参数化
//对请求排队或者记录请求日志,以及支持可撤销的操作。
//命令模式是一种对象行为型模式,其别名为 动作(Action)模式或事物(Transaction)模式

//协议处理类
class HandleClientProtocol{
public:
	//处理机制
	void AddMoney()
	{
		cout << "给玩家增加金币!" << endl;
	}
	//处理增加钻石
	void AddDimond()
	{
		cout << "给玩家增加钻石" << endl;
	}
	//处理玩家装备
	void AddEquipment() {
		cout << "给玩家穿装备" << endl;
	 }

	void addLevel() {
		cout << "给玩家升级" << endl;
	}

};




class AbstractCommand {
public:
	virtual void handle() = 0;//处理客户端请求的接口
};

class Serser {
public:
	void AddRquest(AbstractCommand* command) {
		mCommands.push(command);
	}
	void startHandle()
	{
		while (!mCommands.empty())
		{
			Sleep(100);
			AbstractCommand* pCommand = mCommands.front();
			pCommand->handle();
			mCommands.pop();
		}
	}

public:
	queue<AbstractCommand*>  mCommands;
};

//处理增加金币的请求
class AddMoneyCommand :public AbstractCommand {
public:
	AddMoneyCommand(HandleClientProtocol* pProtocol) {
		this->pProtocol = pProtocol;
	}

	virtual void handle() {
		this->pProtocol->AddMoney();
	}

public:
	HandleClientProtocol* pProtocol;
};

//c处理增加钻石的请求
class AddDimondCommand :public AbstractCommand {
public:
	AddDimondCommand(HandleClientProtocol* pProtocol) {
		this->pProtocol = pProtocol;
	}

	virtual void handle() {
		this->pProtocol->AddDimond();
	}

public:
	HandleClientProtocol* pProtocol;
};

void test01()
{
	HandleClientProtocol* pHandleClientProtocol = new HandleClientProtocol;
	//客户端增加金币的请求
	AbstractCommand* pAddDimondCommand = new AddDimondCommand(pHandleClientProtocol);


	Serser* server = new Serser;
	server->AddRquest(pAddDimondCommand);
	server->startHandle();



}

int main() {

	test01();

	system("pause");
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章