代理模式
代理模式的定义与特点
代理模式的定义:由于某些原因需要给某对象提供一个代理以控制对该对象的访问。这时,访问对象不适合或者不能直接引用目标对象,代理对象作为访问对象和目标对象之间的中介。
代理模式的主要优点有:
其主要缺点是:
那么如何解决以上提到的缺点呢?答案是可以使用动态代理方式
代理模式的结构与实现
代理模式的结构比较简单,主要是通过定义一个继承抽象主题的代理来包含真实主题,从而实现对真实主题的访问,下面来分析其基本结构和实现方法。
1. 模式的结构
代理模式的主要角色如下。
-
抽象主题(Subject)类:通过接口或抽象类声明真实主题和代理对象实现的业务方法。
-
真实主题(Real Subject)类:实现了抽象主题中的具体业务,是代理对象所代表的真实对象,是最终要引用的对象。
-
代理(Proxy)类:提供了与真实主题相同的接口,其内部含有对真实主题的引用,它可以访问、控制或扩展真实主题的功能。
其结构图如图 1 所示。

图1 代理模式的结构图
在代码中,一般代理会被理解为代码增强,实际上就是在原代码逻辑前后增加一些代码逻辑,而使调用者无感知。
根据代理的创建时期,代理模式分为静态代理和动态代理。
#include <iostream> using namespace std; #ifndef SAFE_DELETE #define SAFE_DELETE(p) { if(p){delete(p); (p)=NULL;} } #endif
class SchoolGirl { public: void setname(string name) { name_ = name; } string getname() { return name_; } private: string name_; };
class CGiveGift { public: virtual void GiveDolls() = 0; virtual void GiveFollows() = 0; virtual void GiveChocolates() = 0; };
class Pursuit : public CGiveGift { public: Pursuit(SchoolGirl* schoolgirl) { schoolgirl_ = schoolgirl; } void GiveDolls() { if (schoolgirl_) { cout << "pursuit give dolls to " << schoolgirl_->getname() << "\n"; } } void GiveFollows() { if (schoolgirl_) { cout << "pursuit give follows to " << schoolgirl_->getname() << "\n"; } } void GiveChocolates() { if (schoolgirl_) { cout << "pursuit give chocolates to " << schoolgirl_->getname() << "\n"; } } private: SchoolGirl* schoolgirl_ = nullptr; };
class Proxy : public CGiveGift { public: Proxy(SchoolGirl* schoolgirl) { pursuit_ = new Pursuit(schoolgirl); } ~Proxy() { SAFE_DELETE(pursuit_); } void GiveDolls() { if (pursuit_) { pursuit_->GiveDolls(); } } void GiveFollows() { if (pursuit_) { pursuit_->GiveFollows(); } } void GiveChocolates() { if (pursuit_) { pursuit_->GiveChocolates(); } } private: Pursuit* pursuit_ = nullptr; }; int main() { SchoolGirl* schoolgirl = new SchoolGirl(); schoolgirl->setname("李娇娇"); Proxy* proxy = new Proxy(schoolgirl); proxy->GiveDolls(); proxy->GiveFollows(); proxy->GiveChocolates(); SAFE_DELETE(proxy) SAFE_DELETE(schoolgirl) return 0; }
|