代理模式就用两篇文章来吧!
代理模式之一
//代理模式
//对实体类进行代理,派生实体类,构造虚函数
//有透明和普通代理。透明代理:再代理一次代理类进行封装。
//下面看下强制代理代码(包含了上面的介绍)
class IGamePlayer {
//强制代理的通用接口类
public:
virtual void Login(string user, string password) {}
virtual void KillBose() {}
virtual void Upgrade() {}
virtual IGamePlayer* GetProxy() {}
};
class GamePlayer : public IGamePlayer {
//强制代理的真实角色
private:
string m_name;
IGamePlayer* m_pProxy;
public:
GamePlayer(string _name) {
m_name = _name;
}
IGamePlayer* GetProxy() {
//重点在这,角色类会自动判断是否是自己的代理类
//我的话会用枚举来判断是否是自己的强制代理类
m_pProxy = new IGamePlayer;
return m_pProxy;
}
//接下来的函数就通过指针判断代理类
void KillBose() {
if (IsProxy()) {
cout << m_name << "kill bose";
} else cout << "proxy not right";
}
void Login(string user, string password) {
if (IsProxy()) {
cout << m_name << "login";
} else cout << "proxy not right";
}
void Upgrade() {
if (IsProxy()) {
cout << m_name << "upgrade";
} else cout << "proxy not right";
}
private:
bool IsProxy() {
if (m_pProxy) {
return true;
} else return false;
}
};
class GamePlayerPoxy : public IGamePlayer {
private:
IGamePlayer* m_pGamePlayer;
public:
GamePlayerPoxy(IGamePlayer* _gameplayer) {
m_pGamePlayer = _gameplayer;
}
void KillBose() {
m_pGamePlayer->KillBose();
}
void Login(string user, string password) {
m_pGamePlayer->Login(user, password);
}
void Upgrade() {
m_pGamePlayer->Upgrade();
}
IGamePlayer* GetProxy() {
return this;
}
};
//场景限制
class Client {
static void main() {
IGamePlayer* player = new GamePlayer("demo");
//在这里,实体类只能被指定的代理类所代理
//如果是其他形式创建的类,调用就不会成功
IGamePlayer* poxy = player->GetProxy();
poxy->Login("demo", "123456");
poxy->KillBose();
poxy->Upgrade();
}
};