基本概念
Proxy Pattern: Provide a surrogate or placeholder for another object to control access to it.
实现代码
抽象主体
Subject 声明了主体和代理的共同接口,使得在任何使用主体的地方都可以使用代理。
具体主体
Concrete Subject 代理所代表的真实对象(最终实际想要引用的对象)
代理
Proxy 提供了一个与真实主体相同的接口,因此可以在任何使用真实主体的地方使用代理对象。代理对象通常负责一些额外的功能,例如创建和销毁真实对象等。这些额外功能得代理对象可以在真实主体执行请求前后执行某些操作,决定是否转发请求给真实对象。
测试类
Q & A
What are the different types of proxies?
- Remote proxies
- Virtual proxies
- …
What are the advantages and disadvantages of proxy pattern?
Pros
- Provides a layer of protection for the real object from unnecessary complexity.
- Can control access (such as lazy initialization) and add additional behaviors before forwarding the request.
Cons
- Can add overhead and sometimes make debugging more difficult.
- May cause latency if the proxy and the real subject aren't co-located.