design patterns · structural
Proxy
Provides a surrogate or placeholder for another object to control access to it.
Pattern
Overview
Intent
Provide a surrogate or placeholder for another object to control access to it.
Real-World Analogy
A credit card is a proxy for a bank account - same payment interface, but controls when/how the underlying account is accessed.
When you need to control access to an object - delay its creation, add logging, or restrict who can use it - a proxy implements the same interface as the real object, so the client never knows it is talking to a proxy.
Proxy implements the same interface as RealSubject. The client calls the proxy. The proxy may perform pre/post processing and delegates to the real subject when appropriate. The real subject is transparent to the client.
When to use
Virtual proxies (lazy initialization), remote proxies (RMI, gRPC), protection proxies (access control), caching proxies, AOP frameworks, logging proxies.
When not to
When direct access is fine and no control or pre/post processing is needed.
Participants
Key Insights
- Virtual Proxy: delays expensive object creation until first use
- Protection Proxy: checks permissions before delegating to real subject
- Caching Proxy: caches results of expensive operations
- Java dynamic proxies (java.lang.reflect.Proxy) generate proxies at runtime - foundation of Spring AOP