Proxy
Provide a surrogate or placeholder for another object to control access to it.
Intent
Introduce a stand-in object that controls access to a real subject -- deferring its creation, guarding its operations, or adding cross-cutting concerns -- while presenting the same interface so that clients cannot tell the difference.
Problem
You have an object that is expensive to create, located on a remote server, or requires access control. Allowing unrestricted direct access wastes resources, compromises security, or couples the client to infrastructure details. You need a way to interpose control logic without changing the client or the real object.
Solution
Create a proxy class that implements the same interface as the real subject. The proxy holds a reference (or lazily creates one) to the real subject and forwards requests to it, adding behavior such as lazy initialization, access checks, logging, or caching around each delegation.
Participants
- Subject -- the common interface shared by RealSubject and Proxy
- RealSubject -- the actual object that performs the work
- Proxy -- controls access to the RealSubject; implements the same interface
- Client -- works with the Subject interface, unaware whether it holds a Proxy or the RealSubject
Advantages
- Controls access to the real object without clients knowing
- Enables lazy initialization of heavyweight objects (virtual proxy)
- Can add caching, logging, or access control transparently
- The real object's lifecycle can be managed independently of the client
Disadvantages
- Adds an extra layer of indirection, which can complicate debugging
- Response time may increase due to additional processing in the proxy
- Proxy code can become complex when combining multiple concerns (caching + auth + logging)
- The proxy must stay in sync with the real subject's interface evolution
Real-World Analogy
A credit card is a proxy for your bank account. The store (client) swipes the card (proxy) instead of accessing your cash (real subject) directly. The card performs access control (PIN verification), communicates with the bank, and may apply spending limits -- all before letting the transaction through.
Use Cases
- Virtual proxy: deferring the loading of a high-resolution image until it is scrolled into view
- Protection proxy: checking user permissions before allowing operations on a sensitive resource
- Caching proxy: storing results of expensive database queries and returning cached data on repeat calls
- Remote proxy: representing an object on a different server and marshalling calls over the network
- Logging proxy: recording every method invocation for auditing or debugging purposes
Code Examples
A virtual proxy that lazily loads a heavy image object on first access and a protection proxy that checks permissions before delegating operations.
Related Patterns
Decorator
Attach additional responsibilities to an object dynamically, providing a flexible alternative to subclassing for extending functionality.