C++设计模式 - 代理模式详解二

  • 5.游戏代练收费

上一篇文章提到了小明请游戏代练来帮助自己打游戏升级,但是游戏代练也不是白帮你玩的,小明需要付费给游戏代练。

咱们定义一个付费的接口基类。

class ICost {
public:
	ICost();
	~ICost();

	virtual void money();
};

#include "ICost.h"

ICost::ICost() {
}

ICost::~ICost() {
}

void ICost::money() {

然后让游戏代练继承这个接口,并且实现这个接口

class ProxyStudentPlayer :public IPlayer, public ICost {
public:
	ProxyStudentPlayer(std::string name, std::string account, std::string pwd);
	ProxyStudentPlayer(std::string name,IPlayer* player);
	~ProxyStudentPlayer();

	//登录游戏
	void login()override;

	//玩游戏
	void play()override;

	//升级
	void update()override;

	//退出登录
	void logout()override;

	//游戏代练费用
	void money()override;

private:
	std::string _proxyName;
	IPlayer* _studentPlayer;
};

ProxyStudentPlayer::ProxyStudentPlayer(std::string name, std::string account, std::string pwd)
:IPlayer(account, pwd) {
	_proxyName = name;
	_studentPlayer = new StudentPlayer(account, pwd);
}

ProxyStudentPlayer::ProxyStudentPlayer(std::string name, IPlayer* player) {
	_proxyName = name;
	_studentPlayer = player;
}

ProxyStudentPlayer::~ProxyStudentPlayer() {
		
}

void ProxyStudentPlayer::login() {
	printf("游戏代理:%s  使用", _proxyName.c_str());
	_studentPlayer->login();
}

void ProxyStudentPlayer::play() {
	printf("游戏代理:%s  使用", _proxyName.c_str());
	_studentPlayer->play();
}

void ProxyStudentPlayer::update() {
	printf("游戏代理:%s  使用", _proxyName.c_str());
	_studentPlayer->update();
}

void ProxyStudentPlayer::logout() {
	money();
	printf("游戏代理:%s  使用", _proxyName.c_str());
	_studentPlayer->logout();
}

void ProxyStudentPlayer::money() {
	printf("本次游戏代练需要费用:200元\n");
}

通过代码可以看出,在由此代练退出账号的时候,会调用接口money()这个方法,计算出这个游戏代练需要费用,然后去找小明索取。

客户端代码不用修改,咱们直接运行一下看看结果:
在这里插入图片描述

通过以上示例可以看出,真实的对象和客户端都没有修改,只是修改了代理类,就完成了费用计算的功能。

这样做就解耦对象的核心功能和非核心功能。通过在代理类上添加一些非核心功能实现真实对象的功能扩展。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wb175208

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值