Proxy Design Pattern in Java
Control access to another object through a substitute with the same interface.
What is Proxy?
A proxy can add security, caching, logging, lazy loading, or remote communication before forwarding a call to the real object.
Beginner-friendly Java example
The following example shows the central idea of this pattern in a small, practical scenario.
interface ReportService {
String load(String id);
}
class SecureReportProxy implements ReportService {
private final ReportService target;
SecureReportProxy(ReportService target) {
this.target = target;
}
public String load(String id) {
checkPermission(id);
return target.load(id);
}
private void checkPermission(String id) {
System.out.println("Checking access for " + id);
}
}Benefits and trade-offs
Benefits
- Separates responsibilities clearly.
- Improves flexibility as the application grows.
- Encapsulates structural complexity.
Trade-offs
- Can introduce extra wrapper classes.
- Choose the pattern only when the complexity is real.
When should you use it?
- Access control
- Lazy loading expensive objects
- Caching and logging
- Remote service clients
Key takeawayControl access to another object through a substitute with the same interface. Start with the smallest structure that solves the coupling or composition problem.
