Proxy
Intermediate · 15 min read · Low-Level Design, Structural Patterns
Controlling access: lazy, protection, remote, caching and logging proxies.
The idea in plain words
A Proxy is a stand-in object with the same interface as the real one. Callers talk to the proxy, and the proxy decides when, or whether, to call the real object. It can load things lazily, check permissions, cache results or log calls.
The problem
Some objects need a gatekeeper:
The solution
The proxy implements the same interface, holds (or lazily creates) the real subject, and does something before or after forwarding — or decides not to forward at all.
Kinds of proxy
(Make it thread-safe if shared — see the Singleton lesson's lazy-initialisation idioms.) Hibernate's lazy-loaded entities are virtual proxies.
Dynamic proxies in Java
Writing a proxy class per interface is tedious. Java can generate them at runtime:
Pros and cons
Comparisons
Facade and Proxy both stand in front of something complex and may initialise it themselves, but a proxy is interchangeable with its subject (same interface), while a facade offers a different, simpler one.
Interview questions
- Why doesn't @Transactional work when a method calls another @Transactional method in the same class?
- What kinds of proxies are there?
- When is a remote proxy dangerous?
Further reading
Key takeaways
- A proxy has the same interface as its subject and controls access to it.
- Common kinds: virtual (lazy), protection, remote, caching, logging, smart reference.
- Java dynamic proxies and bytecode libraries power frameworks like Spring and Hibernate.
- Proxy controls access; Decorator adds behaviour; Adapter converts interfaces; Facade simplifies.