版权声明:本文为博主原创文章,未经同意不允许转载! https://blog.csdn.net/wb175208/article/details/84985268
- 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()这个方法,计算出这个游戏代练需要费用,然后去找小明索取。
客户端代码不用修改,咱们直接运行一下看看结果:
通过以上示例可以看出,真实的对象和客户端都没有修改,只是修改了代理类,就完成了费用计算的功能。
这样做就解耦对象的核心功能和非核心功能。通过在代理类上添加一些非核心功能实现真实对象的功能扩展。