Implement Java proxies by preserving the original contract while controlling access, creation, or invocation of the real object.
Proxy: A stand-in object that exposes the same contract as the real object while changing how that object is reached or used.
A simple Java proxy keeps the same interface and owns a reference to the real subject.
1public interface ReportStore {
2 Report load(String id);
3}
4
5public final class CachedReportStoreProxy implements ReportStore {
6 private final ReportStore delegate;
7 private final Map<String, Report> cache = new HashMap<>();
8
9 public CachedReportStoreProxy(ReportStore delegate) {
10 this.delegate = delegate;
11 }
12
13 @Override
14 public Report load(String id) {
15 return cache.computeIfAbsent(id, delegate::load);
16 }
17}
This proxy changes access semantics by caching, while callers still depend on ReportStore.
The proxy should make one access concern explicit:
If it starts changing core business workflow, it is no longer just a proxy.