您的位置:首页 > 编程语言 > C语言/C++

C++编程思想(卷二):设计模式:代理模式

2009-12-10 15:34 288 查看
代理模式:

#include <iostream>
using namespace std;
class ProxyBase {
public:
virtual void f() = 0;
virtual void g() = 0;
virtual void h() = 0;
virtual ~ProxyBase() {}
};
class Implementation : public ProxyBase {
public:
void f() { cout << "Implementation.f()" << endl; }
void g() { cout << "Implementation.g()" << endl; }
void h() { cout << "Implementation.h()" << endl; }
};
class Proxy : public ProxyBase {
ProxyBase* implementation;
public:
Proxy() { implementation = new Implementation(); }
~Proxy() { delete implementation; }
// Forward calls to the implementation:
void f() { implementation->f(); }
void g() { implementation->g(); }
void h() { implementation->h(); }
};
int main()  {
Proxy p;
p.f();
p.g();
p.h();
}


代理模式的一般用途:

远程代理:为不同地址空间的对象提供代理

虚拟代理:根据需要提供一种“惰性初始化”方式来创建高代价的对象

保护代理:当不愿意客户程序员拥有被代理对象的全部访问权限时

巧妙引用:当访问被代理的对象时,增加额外的活动,引用计数就是一个例子
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: