Proxy
20 Mar 2022Intent
Provide a surrogate or placeholder for another object to control access to it.
Also known as
Surrogate
Applicability
Proxy is applicable whenever there is a need for a more versatile or sophisticated references to ab object than a simple pointer. Some situations in which the Proxy pattern is applicable:
- A remote proxy provides a local representative for an object ina different address space.
- A virtual proxy creats expensive objects on demand.
- A protection proxy controls access to the original object.
Structure
Participants
- Proxy: maintains a reference that lets the proxy access the real subject, provides an interface identical to Subject's so that a proxy can be substituted for the real subject, controls access to real subject and may be responsible for creating and deleting it.
- Subject: defines the common interface for RealSubject and Proxy so that a Proxy can be used anywhere a RealSubject is expected.
- RealSubject: defines the real object that the proxy represents.
Collaborations
Proxy forwards requests to RealSubject when appropriate, depending on the kind of proxy.
Sample Code
Related Patterns
- Adapter provides a different interface to the object it adapts, in contrast, a proxy provides the same interface as it's subject.
- Decorator: Although decorators can have similar implementations as proxies, they have a different purpose. A decorator adds one or more responsibilities to an object, whereas a proxy controls access to an object.