Decorator and Proxy
Mid-level Always asked 6 min
On this page
The question
What is the difference between Decorator and Proxy?
30-second answer
They are built the same way: a wrapper with the same type as its target, forwarding calls. The difference is intent. A Decorator adds behavior, and your code composes as many layers as it wants. A Proxy controls access to the target, for a transaction, security or lazy loading, and a framework usually creates it so the client never knows.
Understand it
A call passing through proxy layers
Step by stepThe client holds an OrderService reference, but Spring injected a proxy of the same type. Calling place() enters the proxy first.
View as text
A client box on the left, and a large proxy box around three layers in a row: logging, transaction and the target OrderService. A trace below lists what has happened.
The client holds an OrderService reference, but Spring injected a proxy of the same type. Calling place() enters the proxy first. The call enters the proxy box.
The proxy runs its interceptors in order. Logging records the call, then the transaction interceptor begins a transaction. The trace reads log and BEGIN.
Only now does the real OrderService.place() run, inside the transaction. Its code contains no transaction handling. The target is highlighted, and the trace adds place().
The call returns back through the layers. The transaction commits, or rolls back on a RuntimeException, and logging records the result. The trace adds COMMIT and log.
place() then calls this.charge(). this is the target, not the proxy, so that call skips every layer and @Transactional on charge() does nothing. An arrow leaves the target and returns to it inside the box, away from both layers, and a mark says there is no transaction for that call.
A client box on the left, and a large proxy box around three layers in a row: logging, transaction and the target OrderService. A trace below lists what has happened.
The client holds an OrderService reference, but Spring injected a proxy of the same type. Calling place() enters the proxy first. The call enters the proxy box.
The proxy runs its interceptors in order. Logging records the call, then the transaction interceptor begins a transaction. The trace reads log and BEGIN.
Only now does the real OrderService.place() run, inside the transaction. Its code contains no transaction handling. The target is highlighted, and the trace adds place().
The call returns back through the layers. The transaction commits, or rolls back on a RuntimeException, and logging records the result. The trace adds COMMIT and log.
place() then calls this.charge(). this is the target, not the proxy, so that call skips every layer and @Transactional on charge() does nothing. An arrow leaves the target and returns to it inside the box, away from both layers, and a mark says there is no transaction for that call.
Takeaway: Spring wraps a bean in a proxy of the same type, so advice such as transactions runs around each outside call. A call on this bypasses it.
Decorator stack vs proxy
CompareDecorator: your code stacks wrappers with new, in the order it chooses, and each one adds behavior. new Logging(new Caching(new Jdbc())) is typical.
View as text
A client on the left calls a row of wrappers ending at the real object. Four rows below compare intent, who wraps, how many layers and whether the client knows.
Decorator: your code stacks wrappers with new, in the order it chooses, and each one adds behavior. new Logging(new Caching(new Jdbc())) is typical. The chain is Logging, Caching and Jdbc. The rows read add behavior, your code with new, stack any number, and yes.
Proxy: a framework or factory puts one stand-in in front of the target, to control access, such as a transaction, a security check or lazy loading. The chain is Proxy and Target. The rows read control access, a framework or factory, usually one per object, and no.
A client on the left calls a row of wrappers ending at the real object. Four rows below compare intent, who wraps, how many layers and whether the client knows.
Decorator: your code stacks wrappers with new, in the order it chooses, and each one adds behavior. new Logging(new Caching(new Jdbc())) is typical. The chain is Logging, Caching and Jdbc. The rows read add behavior, your code with new, stack any number, and yes.
Proxy: a framework or factory puts one stand-in in front of the target, to control access, such as a transaction, a security check or lazy loading. The chain is Proxy and Target. The rows read control access, a framework or factory, usually one per object, and no.
Takeaway: They are built the same way, a wrapper with the target's type. Decorator adds behavior you compose yourself; Proxy controls access, usually set up for you.
In code
interface OrderRepository { String find(String id); }
class JdbcOrderRepository implements OrderRepository {
public String find(String id) { return "order-" + id; } // really a SELECT
}
class CachingOrderRepository implements OrderRepository {
private final OrderRepository next;
private final Map<String, String> cache = new HashMap<>();
CachingOrderRepository(OrderRepository next) { this.next = next; }
public String find(String id) { return cache.computeIfAbsent(id, next::find); }
}
class LoggingOrderRepository implements OrderRepository {
private final OrderRepository next;
LoggingOrderRepository(OrderRepository next) { this.next = next; }
public String find(String id) {
System.out.println("find " + id);
return next.find(id);
}
}
OrderRepository repo = new LoggingOrderRepository(new CachingOrderRepository(new JdbcOrderRepository()));static OrderService transactional(OrderService target) {
return (OrderService) Proxy.newProxyInstance(
OrderService.class.getClassLoader(),
new Class<?>[] {OrderService.class},
(proxy, method, args) -> {
System.out.println("begin " + method.getName());
try {
Object result = method.invoke(target, args);
System.out.println("commit");
return result;
} catch (InvocationTargetException e) {
System.out.println("rollback");
throw e.getCause();
}
});
}
OrderService service = transactional(new SimpleOrderService());
service.place("book"); // begin place, the target runs, commitclass CachingRates implements Rates {
private final Rates real;
private final Map<String, BigDecimal> cache = new ConcurrentHashMap<>();
CachingRates(Rates real) { this.real = real; }
@Override public BigDecimal rate(String currency) {
return cache.computeIfAbsent(currency, real::rate); // the real service is called once per currency
}
}Solve it
Add logging, retries and metrics to a payment client you cannot edit
PaymentClient.charge() comes from a shared library. You need a log line per call, up to three retries on timeout and a
latency metric, each switchable by configuration, without touching the library or its callers.
- Match the need to a pattern. Same interface, extra behavior, stackable and optional: Decorator. Each wrapper does one thing and delegates.
- Write one decorator per concern.
LoggingClient,RetryingClientandTimedClienteach implementPaymentClientand hold the next one. - Choose the order on purpose. Timing outside the retries measures what the caller waits; timing inside measures every attempt. Logging outside writes one line per call.
- Compose at wiring time. The configuration decides which wrappers to add; callers still receive a
PaymentClient. - Check. Test each decorator alone with a fake inner client, for example one that times out twice and then succeeds.
class RetryingClient implements PaymentClient {
private final PaymentClient next;
RetryingClient(PaymentClient next) { this.next = next; }
public Receipt charge(Money amount) {
for (int attempt = 1; ; attempt++) {
try { return next.charge(amount); }
catch (PaymentTimeoutException e) { if (attempt == 3) throw e; } // unchecked, from the library
}
}
}
PaymentClient client = new LibraryPaymentClient();
if (config.retries()) client = new RetryingClient(client);
if (config.metrics()) client = new TimedClient(client, meterRegistry); // outside: total time the caller waits
if (config.logging()) client = new LoggingClient(client);How to answer
- Decorator example:
new BufferedInputStream(new FileInputStream(file)). - Proxy example: the object Spring injects for a
@Transactionalbean. - Decorators are layered by the caller; a proxy usually hides the wrapping.
- Interviewers want the intent, since the class diagrams are nearly identical.
Common mistakes
- Saying they are unrelated, or that one uses interfaces and the other does not.
- Claiming that a proxy never adds behavior; it adds behavior to control access, and the difference is intent.
Follow-up questions
How does Spring implement @Transactional and AOP (aspect-oriented programming)?
With a proxy. At startup, a bean post-processor sees the annotation and replaces the bean with a proxy of the same type, built with CGLIB or a JDK dynamic proxy. Callers receive the proxy. On each call it runs an interceptor chain around your method: the transaction interceptor begins a transaction, calls the target, and commits, or rolls back on a RuntimeException.
- Your class contains no transaction code; the advice lives in the proxy.
- It only works on calls that go through the proxy.
- By default, checked exceptions do not trigger a rollback.
See it in the infographic: A call passing through proxy layers
Why does a @Transactional method called from the same class not start a transaction?
Because the advice lives in the proxy, and this is the target. An outside caller goes through the proxy, but this.place() is a plain method call on the real object, so no interceptor runs. It compiles and runs without any error, just outside a transaction. Move the method to another bean, or inject a TransactionTemplate.
- No error is raised, so this tends to show up as a data bug.
- Moving the method to another bean is usually the cleanest fix.
- The same limit applies to
@Cacheable,@Asyncand any proxy-based annotation.
@Service
class OrderService {
public void outer() {
this.place(); // no proxy: runs with no transaction
}
@Transactional
public void place() { }
} See it in the infographic: A call passing through proxy layers
Why use a Decorator instead of a subclass?
A subclass fixes one combination at compile time, so logging, caching and retry in any combination would need a class for each: a class explosion. Decorators compose at runtime, one wrapper per concern, so three wrappers cover all those combinations. It is composition over inheritance applied to added behavior, and the wrapped class needs no change.
- N concerns need N decorators, against up to 2^N subclasses.
- Order matters, since a cache around logging differs from logging around a cache.
- A long chain can make stack traces and debugging harder.
Does the order of decorators matter?
Yes. Calls enter from the outside in, and results come back from the inside out. With logging outside a cache, every call is logged, including hits. With the cache outside logging, a hit never reaches the logger, so you log only the misses. Choose the order for what you want to see, and write it down where the object is composed.
- The outermost wrapper sees every call.
- Anything inside a cache runs only on a miss.
- With Spring aspects,
@Ordersets the same kind of order.
// Logs every call, including cache hits
new LoggingOrderRepository(new CachingOrderRepository(jdbc));
// Logs only cache misses
new CachingOrderRepository(new LoggingOrderRepository(jdbc)); What kinds of proxy are there, and what is each one for?
A virtual proxy delays creating something expensive until first use, like Hibernate's lazy-loaded entities. A protection proxy checks permissions before forwarding, like method security. A remote proxy makes a network call look local, like a Feign client. A smart proxy adds work around the call, like Spring's transaction proxy. All of them keep the target's type.
- Each kind controls access for a different reason.
- Hibernate's
getReferenceByIdreturns a virtual proxy. LazyInitializationExceptionhappens when that proxy loads after the session closed.
What is the difference between a JDK (Java Development Kit) dynamic proxy and CGLIB (Code Generation Library)?
A JDK proxy implements the target's interfaces, so it can only be used through those interfaces; casting it to the concrete class fails. CGLIB generates a subclass, so it works without an interface but cannot proxy final classes or final methods. Spring Boot uses CGLIB by default.
Why does a private or final method skip @Transactional?
A CGLIB proxy works by overriding methods in a subclass, and a private or final method cannot be overridden. A call to one runs directly, with no advice. It is often silent, so the method looks transactional and is not. Keep transactional methods overridable, and non-private.
Where does the JDK use Decorator?
java.io is built on it: BufferedInputStream, DataInputStream and GZIPInputStream all wrap another InputStream. Collections.unmodifiableList and Collections.synchronizedList wrap any List and keep the type. The wrapper can be stacked, and the concrete classes underneath stay unaware.
Check yourself
Show answers
- No, because this is the target, not the proxy.: Correct. The advice lives in the proxy, and a call on this never reaches it.
- Yes, because the annotation is on the method.: Incorrect. An annotation does nothing alone; the proxy reads it, and this call skips the proxy.
- It fails at startup with an error.: Incorrect. It compiles and starts normally, which is why this mistake goes unnoticed.
Show answers
- BufferedInputStream around a FileInputStream: Correct. You compose it yourself, and it adds buffering behind the same InputStream type.
- A lazy-loading entity from Hibernate: Incorrect. That controls when data loads, and Hibernate creates it, so it is a Proxy.
- The bean Spring injects for a @Transactional class: Incorrect. A framework creates it to control the call, so it is a Proxy.
Show answers
- It is an OrderService, but it is not a SimpleOrderService.: Correct. It implements only the interface, so an instanceof check on the class is false.
- It is a subclass of SimpleOrderService.: Incorrect. That describes a CGLIB proxy, which works by generating a subclass.
- It is the same object as the target.: Incorrect. It is a separate object that forwards calls to the target.