C++设计模式之命令模式

命令模式:讲一个请求封装为一个对象,从而让我们可用不同的请求对客户进行参数化;对请求排队或者记录请求日志,命令模式是一种行为性模式。命令模式可以将请求发送者和接受者完全解耦,发送者和接收者之间没有直接引用关系。

//协议处理类
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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值