Proxy Pattern
Provide a surrogate or placeholder for another object to control access.
📌 Key IdeaClient talks to Proxy implementing the same interface as RealSubject. Proxy may defer creation (virtual), enforce access (protection), hide remote calls (RMI style), or add reference counting / logging.
Visual
🛡 Same interface, controlled access
interface Image { void draw(); }
class ProxyImage implements Image {
private RealImage real; // lazy create
void draw() {
if (real == null) real = new RealImage(path);
real.draw();
}
}Virtual proxy: expensive object created only when first needed.
When to Use
- Lazy loading — delay heavy resource until first use.
- Access control — permission checks before delegating.
- Remote object — local proxy marshals network calls.
- Logging / caching around expensive operations.
When NOT to Use
- You need to add features transparently in layers — often Decorator intent.
- Proxy indirection hurts latency when always hitting real subject anyway.
Anti-Pattern (What NOT to Do)
Eager load on startupBadjava
class Page {
private final HeavyChart chart = new HeavyChart(); // always paid for
}User may never open the chart tab.
The Right Way
Virtual proxy — create on first useGoodjava
class ChartProxy implements Chart {
private HeavyChart real;
public void draw() {
if (real == null) real = new HeavyChart();
real.draw();
}
}Same interface as real subject; Spring/JPA often enhance this with bytecode.
Pros & Cons
👍 Pros
- Separates concerns of access control / caching from subject logic.
- Can protect real subject from misuse.
👎 Cons
- Extra indirection — debugging one more hop.
- Easy to confuse with Decorator — document intent.
Common Confusions Cleared Up
Proxy vs Decorator
Proxy controls access to often one heavy or remote subject. Decorator stacks features on an object. Same composition structure — intent differs (GoF stress this interview trap).
Interview Q&A
Likely Follow-up Questions
- Dynamic proxy
InvocationHandlerin Java — how it maps to Proxy pattern?
Quick Cheat Sheet
IntentSurrogate controls access to real object.
vs DecoratorAccess vs add behaviour.
SpringAOP proxies around beans.