定义
类图
时序图
角色定义
- 抽象主体角色:抽象类或者接口,普通业务的定义
- 具体主体角色:被代理角色,业务逻辑的具体执行者
- 代理主体角色:委托类,代理类
优缺点
- 优点
- 职责清晰,实现好内部结构即可,具体客户要求由代理进行分化
- 高扩展性:具体主体角色随时变化,只要实现了接口,都可以由代理来处理
应用场景
实现
#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;
}
#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;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
2021-04-10 结构体的比较
2021-04-10 引用在汇编层次上面的解释
2018-04-10 1015. Reversible Primes (20)