Proxy
Intent
Provides a substitute that controls access to another object.
Problem
A heavy database object should only be created when actually needed, and access should be logged.
Solution
A proxy with the same interface creates, caches, checks or logs, then forwards to the real object.
Real-world analogy
A credit card stands in for your bank account, which stands in for cash. The shop accepts it the same way.
Structure
Hover or tap a numbered role to highlight it in the diagram.
- 1ServiceInterface — Service Interface is shared by the service and the proxy.
- 2Service — Service contains the real business logic.
- 3Proxy — Proxy holds a reference to the service. It adds lazy loading, caching, logging or access control, then delegates.
- 4Client — Client uses the service and the proxy through the same interface.
Code example
Applicability
Use Proxy when lazy initialisation (virtual proxy).
Use Proxy when access control.
Use Proxy when remote services.
Use Proxy when logging and caching.
Pros and cons
Pros
- Control the service without clients knowing
- Works even if the service isn't ready
Cons
- Possible response delay
- More classes
Check yourself
Add caching and access checks in front of a slow remote image service without changing its clients.
Saved in this browser only. Part of Structural patterns (0/7).