Proxy
structural
Provides a surrogate or placeholder for another object to control access to it.
Intent
The Proxy pattern provides a surrogate or placeholder for another object to control access to it.
Motivation
When you need to control access to an object, add additional functionality when accessing an object, or delay the creation of an expensive object, the Proxy pattern is useful.
Structure
The pattern involves a Proxy class that controls access to the real subject. Both Proxy and RealSubject implement the same interface, so the proxy can be used anywhere the real subject is expected.
Participants
- •Subject - defines the common interface for RealSubject and Proxy
- •RealSubject - defines the real object that the proxy represents
- •Proxy - maintains a reference to the RealSubject and controls access to it
Pros
- ✓Controls access to the object
- ✓Can add functionality without changing the object
- ✓Supports lazy initialization
- ✓Follows Open/Closed Principle
Cons
- ✗Increases complexity
- ✗May introduce latency
Use Cases
Lazy loading of resources
Access control and security
Remote object access
Caching expensive operations
Logging and monitoring
Implementation Tips
Considerations
- •Decide what type of proxy (virtual, protection, remote, etc.)
- •Consider thread safety for virtual proxies
- •Think about caching strategies
- •Plan for error handling
Tips
- •Keep the proxy interface identical to the subject
- •Consider using lazy initialization
- •Document what the proxy adds or restricts
- •Use proxies for cross-cutting concerns