命令模式:讲一个请求封装为一个对象,从而让我们可用不同的请求对客户进行参数化;对请求排队或者记录请求日志,命令模式是一种行为性模式。命令模式可以将请求发送者和接受者完全解耦,发送者和接收者之间没有直接引用关系。
//协议处理类
class HandleClientProtocol{
public:
void AddMoney(){
cout << "给玩家增加金币" <<endl;
}
void AddDiamond(){
cout << "给玩家增加钻石" <<endl;
}
void AddEquipment(){
cout << "给玩家增加装备" <<endl;
}
};
//命令接口
class AbstractCommand{
public:
virtual void handle() = 0; // 处理客户端请求的接口
};
class AddMoneyCommand : public AbstractCommand{
public:
AddMoneyCommand(HandleClientProtocol* protocol){
this->pProtocol = protocol;
}
virtual void handle(){
this->pProtocol->AddMoney();
}
public:
HandleClientProtocol* pProtocol;
};
class AddDiamondCommand : public AbstractCommand{
public:
AddDiamondCommand(HandleClientProtocol* protocol){
this->pProtocol = protocol;
}
virtual void handle(){
this->pProtocol->AddDiamond();
}
public:
HandleClientProtocol* pProtocol;
};
class AddEquipmentCommand : public AbstractCommand{
public:
AddEquipmentCommand(HandleClientProtocol* protocol){
this->pProtocol = protocol;
}
virtual void handle(){
this->pProtocol->AddEquipment();
}
public:
HandleClientProtocol* pProtocol;
};
//服务器程序
class Server{
public:
void AddRequest(AbstractCommand* command){
mCommand.push(command);
}
void StartRequest(){
while(!mCommand.empty()){
AbstractCommand* command = mCommand.front();
command->handle();
mCommand.pop();
}
}
public:
queue<AbstractCommand*> mCommand;
};
int main(){
Server* server = new Server;
HandleClientProtocol* protocol = new HandleClientProtocol;
AbstractCommand* addmoney = new AddMoneyCommand(protocol);
AbstractCommand* adddiamond = new AddDiamondCommand(protocol);
AbstractCommand* addequipment = new AddEquipmentCommand(protocol);
server->AddRequest(addmoney);
server->AddRequest(adddiamond);
server->AddRequest(addequipment);
server->StartRequest();
return 0;
}