命令模式(c++)

#include<iostream>
#include<queue>
using namespace std;

class HandleClientProtocol {
public:
	//处理金币
	void AddMoney() {
		cout << "增加金币" << endl;
	}
	//增加砖石
	void AddDiamond() {
		cout << "增加砖石" << endl;
	}
	//处理玩家装备
	void AddEquipment() {
		cout << "给玩家穿装备" << endl;
	}
	//处理玩家升级
	void AddLevel() {
		cout << "给玩家升级" << endl;
	}
};
//命令接口
class AbstractCommand {
public:
	virtual void handle() = 0;//处理客户端请求的接口
};
//增加金币
class AddMoneyCommand :public AbstractCommand {
public:
	AddMoneyCommand(HandleClientProtocol* wp) {
		p = wp;
	}
	virtual void handle() {
		p->AddMoney();
	}
private:
	HandleClientProtocol* p;
};
//增加砖石
class AddDiamondCommand :public AbstractCommand {
public:
	AddDiamondCommand(HandleClientProtocol* wp) {
		p = wp;
	}
	virtual void handle() {
		p->AddDiamond();
	}
private:
	HandleClientProtocol* p;
};
//给玩家穿装备
class AddEquipmentCommand :public AbstractCommand {
public:
	AddEquipmentCommand(HandleClientProtocol* wp) {
		p = wp;
	}
	virtual void handle() {
		p->AddEquipment();
	}
private:
	HandleClientProtocol* p;
};
//给玩家升级
class AddLevelCommand :public AbstractCommand {
public:
	AddLevelCommand(HandleClientProtocol* wp) {
		p = wp;
	}
	virtual void handle() {
		p->AddLevel();
	}
private:
	HandleClientProtocol* p;
};

//服务器
class Server {
public:
	void addRequest(AbstractCommand* command) {
		m_Commands.push(command);
	}
	void startHandle() {
		while (!m_Commands.empty()) {
			AbstractCommand* command = m_Commands.front();
			command->handle();
			m_Commands.pop();
		}
	}
private:
	queue<AbstractCommand*> m_Commands;
};

int main() {
	HandleClientProtocol* hcp = new HandleClientProtocol;
	AbstractCommand* ac = new AddMoneyCommand(hcp);
	Server* s = new Server;
	s->addRequest(ac);
	s->startHandle();
	delete ac;

	ac = new AddDiamondCommand(hcp);
	s->addRequest(ac);
	s->startHandle();
	delete ac;

	ac = new AddEquipmentCommand(hcp);
	s->addRequest(ac);
	s->startHandle();
	delete ac;

	ac = new AddLevelCommand(hcp);
	s->addRequest(ac);
	s->startHandle();
	delete ac;

	delete hcp;
	delete s;

	cin.get();
	return 0;
}

  

posted @ 2024-03-25 17:53  dmfsimle  阅读(2)  评论(0编辑  收藏  举报