定义
- 为其他对象提供一种代理以控制对这个对象的访问
类图
时序图
角色定义
- 抽象主体角色:抽象类或者接口,普通业务的定义
- 具体主体角色:被代理角色,业务逻辑的具体执行者
- 代理主体角色:委托类,代理类
优缺点
- 优点
- 职责清晰,实现好内部结构即可,具体客户要求由代理进行分化
- 高扩展性:具体主体角色随时变化,只要实现了接口,都可以由代理来处理
应用场景
- 游戏代理服务器
实现
- example 1
#include<iostream>
using namespace std;
class Subject {
public:
virtual void func(){
cout << "Subject" << endl;
}
};
class RealSubject : public Subject{
public:
virtual void func(){
cout << "RealSubject" << endl;
}
};
class Proxy : public Subject{
public:
virtual void func()
{
cout << "Proxy" << endl;
m_real.func();
}
private:
RealSubject m_real;
};
int main()
{
Proxy CProxy;
CProxy.func();
return 0;
}
- example 2
// 大话设计模式样例
#include<iostream>
#include<string>
using namespace std;
class SchoolGirl
{
public:
string getName(){
return m_strName;
}
void setName(string name){
m_strName = name;
}
private:
string m_strName;
};
class Gift
{
public:
void giveDolls();
void giveFlowers();
void giveChocolate();
};
class Pursuit : public Gift
{
public:
Pursuit(SchoolGirl* pGirl) : m_Girl(pGirl){}
string getName(){
return m_strName;
}
void setName(string strName){
m_strName = strName;
}
void giveDolls(){
cout << m_strName << "give [" << m_Girl->getName() << "] Dolls" << endl;
}
void giveFlowers(){
cout << m_strName << "give [" << m_Girl->getName() << "] flowers" << endl;
}
void giveChocolate(){
cout << m_strName << "give [" << m_Girl->getName() << "] chocolate" << endl;
}
private:
SchoolGirl* m_Girl;
string m_strName;
};
class Proxy : public Gift
{
public:
Proxy(SchoolGirl* pGirl){
m_Pur = new Pursuit(pGirl);
m_Pur->setName("胡汉三");
}
void giveDolls(){
m_Pur->giveDolls();
}
void giveFlowers(){
m_Pur->giveFlowers();
}
void giveChocolate(){
m_Pur->giveChocolate();
}
private:
Pursuit* m_Pur;
};
int main()
{
SchoolGirl* pJiaoJiao = new SchoolGirl;
pJiaoJiao->setName("李娇娇");
Proxy* pDali = new Proxy(pJiaoJiao);
pDali->giveDolls();
pDali->giveFlowers();
pDali->giveChocolate();
return 0;
}
标签:string,giveDolls,getName,代理,模式,public,strName,设计模式,void
From: https://www.cnblogs.com/wanghao-boke/p/17302276.html