1、什么是代理模式?
简而言之:代理模式就是在访问对象时,引入一定程度的间接性,因为这种间接性,可以附加多种用途。
GoF描述:
代理模式(Proxy):为其他对象提供一种代理以控制对这个对象的访问。
2、代理模式的适用场景?
1、远程代理
为一个对象在不同的地址空间提供局部代表,这样,可以隐藏一个对象存在于不同地址空间的事实。(具体实际应用,还不了解,期待后期学习~~)
2、虚拟代理
根据需要创建开销很大的对象,通过他来存放实例化需要很长时间的真实对象,这样可以达到性能的最优化。
3、安全代理
用来控制真实对象访问时的权限。一般用于对象应该有不同的访问权限的时候。
4、智能指引
当调用真实的对象时,代理处理另外一些事。如:当第一次引用一个持久对象时,将它装入内存。
或计算真实对象的引用次数,当该对象没有引用时,可以自动释放它。
或访问一个实际对象前,检查是否已经锁定它,以确保其他对象不能改变它。
他们都是通过代理在访问一个对象时附加一些内务处理。
3、怎样使用代理模式?
初级,boy找代理追girl
4、实例
1、IGiveGift.h 公共接口函数
#pragma once
class IGiveGift
{
public:
virtual void giveDools() = 0;
virtual void giveFlowers() = 0;
virtual void giveChocolate() = 0;
};
2、Pursuit.h 追求者
#pragma once
#include "SchoolGirl.h"
#include "IGiveGift.h"
#include <iostream>
#include <string>
using namespace std;
class Pursuit
:public IGiveGift
{
public:
Pursuit(SchoolGirl* girl);
public:
void giveDools();
void giveFlowers();
void giveChocolate();
private:
SchoolGirl* mm;
};
Pursuit::Pursuit(SchoolGirl* girl)
:mm(girl)
{
}
void Pursuit::giveDools()
{
cout << mm->getName() << ",送你手办" << endl;
}
void Pursuit::giveFlowers()
{
cout << mm->getName() << ",送你花花" << endl;
}
void Pursuit::giveChocolate()
{
cout << mm->getName() << ",送你糖糖" << endl;
}
3、Proxy.h 代理
#pragma once
#include "SchoolGirl.h"
#include "IGiveGift.h"
#include "Pursuit.h"
#include <iostream>
using namespace std;
class Proxy
:public IGiveGift
{
public:
Proxy(SchoolGirl* girl);
public:
void giveDools();
void giveFlowers();
void giveChocolate();
private:
Pursuit* boy;
};
Proxy::Proxy(SchoolGirl* girl)
{
boy = new Pursuit(girl);//这里是实现代理的重要地方1
}
void Proxy::giveDools()
{
boy->giveDools();//这里是实现代理的重要地方2
}
void Proxy::giveFlowers()
{
boy->giveFlowers();
}
void Proxy::giveChocolate()
{
boy->giveChocolate();
}
4、SchoolGirl.h 被追求者
#pragma once
#include<iostream>
#include<string>
using namespace std;
class SchoolGirl
{
public:
string getName() { return name; }
void setName(const string& _name) { name = _name;}
private:
string name;
};
5、测试
#include "Proxy.h"
#include "Pursuit.h"
#include "SchoolGirl.h"
void test()
{
SchoolGirl* girl = new SchoolGirl();
girl->setName("墨白");
Proxy* p1 = new Proxy(girl);
p1->giveDools();
p1->giveFlowers();
p1->giveChocolate();
}
int main()
{
test();
system("pause");
return 0;
}
此为《大话设计模式》学习心得系列 P58~~