/*代理模式:控制对真实对象的访问,有别于装饰模式(动态添加功能)*/
//代理对象与真实对象继承同一个抽象接口,有相同的接口,所以它能够在任何时刻都能够代理真实对象。
//代理角色内部包含有对真实对象的引用,所以她可以操作真实对象,同时也可以附加其他的操作
#include <iostream>
using namespace std;
class Play
{
public:
virtual ~Play(){}
virtual void play1() = 0;
virtual void play2() = 0;
};
class Player : public Play //真实对象
{
public:
void play1(){cout<<"1v1"<<endl;}
void play2(){cout<<"5v5"<<endl;}
};
class ProxyPlayer : public Play //代理对象
{
public:
ProxyPlayer(int lev) : lever(lev)
{
player = new Player();
}
~ProxyPlayer()
{
delete player;
player = NULL;
}
void play1()
{
if(lever >= 1){ //控制真实对象的访问
player->play1();
}else{
cout<<"Permission denied"<<endl;
}
}
void play2()
{
if(lever >= 5){
player->play2();
}else{
cout<<"Permission denied"<<endl;
}
}
private:
Player* player; //真实对象的引用
int lever;
};
int main()
{
ProxyPlayer* player0 = new ProxyPlayer(0);
ProxyPlayer* player3 = new ProxyPlayer(3);
ProxyPlayer* player6 = new ProxyPlayer(6);
player0->play1();
player3->play1();
player3->play2();
player6->play1();
player6->play2();
delete player0;
delete player3;
delete player6;
return 0;
}
设计模式-代理模式
最新推荐文章于 2024-05-16 17:20:27 发布