design patterns ·
Proxy
Provides a surrogate or placeholder for another object to control access to it.
Theory
Explanation
Intuition first, formal definition second. Skim the bullets if you already know this; read the prose if you don't.
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.
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