#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;
}
設計模式 --命令模式
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.