【设计方式】之代理模式(Proxy)
发布时间: 2012-08-26 16:48:05 作者: rapoo
【设计模式】之代理模式(Proxy)
代理模式的定义为:为其他对象提供一个代理来控制对它的访问。
英文定义:Provide a surrogate or placeholder for another object to control access to it.
这个中文定义没有很好的反映出原本的意思。英文定义中的surrogate与placeholder都有代理的意思。但是他们之间肯定存在微妙的差别。
以下翻译结果,来自有道
surrogate- n. 代理;代用品;遗嘱检验法官
- vt. 代理;指定某人为自己的代理人
- adj. 代理的;替代的
placeholdern. 占位符
我的理解是,surrogate是代理中动的一方面,而placeholder则是静的一面。
代理模式有很多分类:Remote Proxy A remote proxy provides a local representative for an object in a difference address space. Remote proxies are responsible for encoding a request and its arguments and for sending the encoded request to the real subject in a difference address space.
Virtual Proxy A virtual proxy creates expensive objects on demand. Virtual proxies may cache additional information about the real subject so that they can postpone accessing it.
Protection Proxy A protection proxy controls access to the original object. Protection proxies check that the caller has the access permissions required to perform a request.
Smart Reference A smart reference is a replacement for a bare pointer that performs additional actions when an object is accessed.
除了以上比较重要的用途外,还有以下类型:
Firewall ProxyCaching ProxySynchronization ProxyComplexity Hidding ProxyCopy-On-Write Proxy
可见Proxy的用途是非常广泛的。
Proxy可以与real subject继承自同一基类,这样任何用到proxy的地方,都可已用real subject来代替,这一点与decorator模式非常相似,但是他们的intent是不同的。
以下例子是利用java提供的Proxy实现的Protection Proxy。
定义subject对应接口