所谓代理,就是把自己的事情交给别人去做,也就是间接实现自己的目的。书本上对于代理模式(proxy)的定义为:为其他对象提供一种代理以控制对这个对象的访问。其实这个模式挺好理解的,就是相当于在一个类里面实现另一个类的方法,它们的功能是一样的,所以我们可以抽象出一个接口,让本类和代理类都继承它,然后在本类里实现接口里的方法,在代理类的方法里调用本类的方法,然后通过代理类来实现本类的功能。
下面是实践书本上的例子:
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
class IGiveGife
{
public:
virtual void GiveDolls()=0;
virtual void GiveFlowers()=0;
virtual void GiveChocolate()=0;
};
class SchoolGirl
{
public:
SchoolGirl();
SchoolGirl(string name)
{
this->name = name;
}
// private:
string name;
};
class pursuit : public IGiveGife
{
public:
pursuit();
pursuit(SchoolGirl *mm)
{
this->mm = mm;
}
void GiveDolls()
{
cout<<mm->name<<" "<<"give you dolls"<<endl;
}
void GiveFlowers()
{
cout<<mm->name<<" "<<"give you flowers"<<endl;
}
void GiveChocolate()
{
cout<<mm->name<<" "<<"give you chocolate"<<endl;
}
private:
SchoolGirl *mm;
};
class proxy : public IGiveGife
{
public:
proxy();
proxy(SchoolGirl *mm)
{
gg = new pursuit(mm);
}
void GiveDolls()
{
gg->GiveDolls();
}
void GiveFlowers()
{
gg->GiveFlowers();
}
void GiveChocolate()
{
gg->GiveChocolate();
}
private:
pursuit *gg;
};
int _tmain(int argc, _TCHAR* argv[])
{
SchoolGirl *mm = new SchoolGirl("jiaojiao");
proxy pp(mm);
pp.GiveChocolate();
pp.GiveDolls();
pp.GiveFlowers();
system("pause");
return 0;
}
至于我们该什么时候是用代理模式呢,书本中给出了3种情况:
1、远程代理,也就是为一个对象在不同的地址空间提供局部代表。这样可以隐藏一个对象存在于不同地址空间的事实。
2、虚拟代理,是根据需要创建开销很大的对象。通过它来存放实例化需要很长时间的真实对象。
3、安全代理,用来控制真实对象访问时的权限。
4、智能指引,是指当调用真实的对象时,代理处理另外一些事情。
其实看了那么多理论,感觉还是迷迷糊糊的,关键还是自己以后再项目中遇到问题,回过来思考并结合这些模式可能才能真正理解。自己好好加油吧