代理模式:为其他对象提供一种代理以控制对这个对象的访问。
解决了直接访问该对象所带来的问题。
增加了中间层,实现了与被代理类的组合。
优点:职责清晰;扩展性强;智能化。
缺点:增加了类,可能造成处理的速度变慢;增加了额外的类,实现变得复杂。
适用于:远程代理;虚拟代理;Copy-on-Write 代理;保护(Protect or Access)代理;Cache代理;防火墙(Firewall)代理;同步化(Synchronization)代理;智能引用(Smart Reference)代理。
#include <iostream>
#include <string>
using namespace std;
class SchoolGirl
{
public:
SchoolGirl(string name)
{
this->_name = name;
}
public:
string _name;
};
class GiveLift
{
public:
void GiveDolls();
void GiveFlowers();
void GiveChocolate();
};
class Pursuit : public GiveLift
{
public:
Pursuit(SchoolGirl* mm)
{
this->_mm = mm;
}
void GiveDolls()
{
cout << _mm->_name << "送你洋娃娃" << endl;
}
void GiveFlowers()
{
cout << _mm->_name << "送你鲜花" << endl;
}
void GiveChocolate()
{
cout << _mm->_name << "送你巧克力" << endl;
}
private:
SchoolGirl* _mm;
};
class Proxy
{
public:
Proxy(SchoolGirl* mm)
{
gg = new Pursuit(mm);
}
void GiveDolls()
{
gg->GiveDolls();
}
void GiveFlowers()
{
gg->GiveFlowers();
}
void GiveChocolate()
{
gg->GiveChocolate();
}
private:
Pursuit* gg;
};
int main()
{
SchoolGirl* jiaojiao = new SchoolGirl("李娇娇");
Proxy* daili = new Proxy(jiaojiao);
daili->GiveDolls();
daili->GiveFlowers();
daili->GiveChocolate();
return 0;
}