代理模式:为其它对象提供一种代理以控制对这个对象的访问。代理模式类图如下:client想要访问realsubject类时,可以通过proxy类访问。realsubject和proxy继承自subject父类,subject类中定义了统一的接口,realsubject定义接口具体实现,proxy接口调用该实现。
追求者Persuit想要追求SchoolGirl,胆子比较小,只能通过Proxy去追。代码实现如下:
#include<exception>
#include <iostream>
#include<string>
using namespace std;
class GiveGift
{
public:
virtual void giveFlowers() = 0;
virtual void giveDolls() = 0;
virtual void giveChocolate() = 0;
virtual ~GiveGift(){};
};
class Persuit :public GiveGift
{
public:
Persuit(SchoolGirl iGirl):m_girl(iGirl){}
void giveFlowers()
{
cout << "give " + m_girl.getName() + " flowers" << endl;
}
void giveDolls()
{
cout << "give " + m_girl.getName() + " dolls" << endl;
}
void giveChocolate()
{
cout << "give " + m_girl.getName() + " chocolates" << endl;
}
private:
SchoolGirl m_girl;
};
class Proxy :public GiveGift
{
public:
Proxy(Persuit iPersuit):m_persuit(iPersuit){}
void giveFlowers()
{
m_persuit.giveFlowers();
}
void giveDolls()
{
m_persuit.giveDolls();
}
void giveChocolate()
{
m_persuit.giveChocolate();
}
private:
Persuit m_persuit;
};
int main()
{
SchoolGirl girl("sjx");
Persuit persuit(girl);
Proxy proxy(persuit);
proxy.giveFlowers();
proxy.giveDolls();
proxy.giveChocolate();
system("pause");
}
代理模式本质上是提供代理完成间接访问对象。