Published
- 8 min read
Decorator Pattern in Java: Wrappers That Always Call Through
One wrapper per extra, each with the same interface as the client it holds: by hand, in the java.io streams you already stack, and in a Spring config with @Primary.
Your interviewer asks: you wrap a payment client in a logger, then wrap that in a retry, and each one calls the next. Is that a Chain of Responsibility?
If you said yes, that’s the trap. In a chain, a handler can stop the request. A wrapper never does: it adds its one job around the call and always passes it on, so the client inside does the real work every time. That is the Decorator pattern. It is the question the Chain of Responsibility post ended on.
A subclass for every combination
The usual first try is subclasses. One class that logs, one that retries, and one more that does both:
class LoggingGateway
extends BankGateway {}
class RetryingGateway
extends BankGateway {}
class LoggingRetryingGateway
extends BankGateway {}
Now add metrics, and you need a class for every combination: three extras make seven classes, and a fourth makes fifteen. Each combination is fixed when you compile, so switching retries off for one caller means one more class, and the order of the extras is baked into each class’s name.
The Decorator pattern
The Decorator pattern turns each extra class into a wrapper. Every wrapper has the same interface as the client:
interface Gateway {
Receipt charge(long amt);
}
It holds a client inside, and it adds its one job around the call:
class Logged implements Gateway {
final Gateway inner;
Logged(Gateway inner) {
this.inner = inner;
}
public Receipt charge(long amt) {
log("charge " + amt);
return inner.charge(amt);
}
}
The retry is another one. It keeps the code short with a single retry; a real one counts attempts and waits between them, and its second call needs an idempotency key (more on that below):
class Retried implements Gateway {
final Gateway inner;
// constructor: the same
public Receipt charge(long amt) {
try {
return inner.charge(amt);
} catch (Timeout e) {
return inner.charge(amt);
}
}
}
Then you stack them at runtime, in the order you need:
Gateway gateway =
new Logged(
new Retried(
new BankGateway()));
gateway.charge(4900);
Metrics? One more wrapper. Three extras are three classes, not seven, and any stack of them is one line of
wiring. The caller holds a Gateway and can’t tell how many wrappers it is talking to. Here the bank’s first call
times out, and the retry hides it:
/CodeVxDev
decorator
java Decorator.java
16:6:27
The textbook calls the interface the component, BankGateway the concrete component, and each wrapper a
decorator. The definition interviewers like is “adds behaviour to an object at runtime, without changing its
class”, and the subclasses above are why that matters.
Not a chain, and not a proxy
Decorator, Chain of Responsibility and Proxy all look alike in code: an object that holds another object of the same type and calls it. What separates them is what the wrapper is allowed to do with the call:
| Decorator | Chain of Responsibility | Proxy | |
|---|---|---|---|
| Its job | Adds one thing around the call | Decides whether the request goes on | Controls access to the object behind it |
| Can it stop the call? | Never: the client inside always runs | Yes: any handler can end it | Yes: a wrong PIN, a cache hit, an open circuit |
| How many | A stack of any depth, in any order | A line of handlers | Usually one, in front of the object |
| Who puts it there | The code that stacks them | A list, often one Spring builds | A framework, or the proxy itself |
Library names don’t follow this line. Resilience4j calls its circuit breaker and rate limiter decorators, although an open breaker refuses the call, which by the table above makes it a proxy. In an interview, say what the wrapper does with the call: adds to it, or decides whether it happens at all.
You already use it: java.io
You’ve been using these for years. A buffered stream around a file stream, a zip stream around that:
InputStream in =
new GZIPInputStream(
new BufferedInputStream(
new FileInputStream(f)));
Each one is an input stream wrapping another input stream. BufferedInputStream reads ahead in big chunks,
GZIPInputStream unzips, and the code that reads from in sees one InputStream. Both extend FilterInputStream,
the JDK’s base class for stream decorators.
Not every wrapper in java.io is a decorator. InputStreamReader turns bytes into characters, a different
interface, so it is an adapter, which a later episode covers. Outside java.io, Collections.synchronizedList is a
decorator: it wraps a list and takes a lock around every call. Collections.unmodifiableList looks the same, but it
refuses writes, so it is a proxy.
In Spring: stack them once, in a config
In production, a Spring config stacks them once, and everyone who asks for the gateway gets the wrapped one:
@Bean
Gateway gateway(BankGateway bank) {
return new Logged(
new Retried(bank));
}
The catch is that the plain gateway is a bean too. BankGateway implements Gateway, so Spring finds two beans of
that type, and you mark the wrapped one primary:
@Bean
@Primary
Gateway gateway(BankGateway bank) {
return new Logged(
new Retried(bank));
}
Without @Primary, what a caller gets depends on the name of its constructor parameter, because Spring falls back
to matching that name against bean names. On Spring Framework 7.0.10, Gateway gateway gets the wrapped one,
Gateway paymentGateway fails at startup with NoUniqueBeanDefinitionException, and Gateway bankGateway gets the
plain client without a word: no logging, no retry. With @Primary, all three get the wrapped gateway.
Spring also ships the pattern by name. A TaskDecorator wraps every task an executor runs, and the usual one copies
the logging context (MDC, the trace ID) onto the thread that runs an @Async method.
Before you ship it
The order of the wrappers changes what happens
Logged(Retried(bank)) and Retried(Logged(bank)) hold the same three objects, and they log differently. With the
logger outside the retry, a charge is logged once however many tries it takes; with the logger inside, every try is
logged. Neither is wrong, but you should choose. Metrics follow the same rule: inside the retry they count attempts,
outside they count charges.
A retried charge needs an idempotency key
A charge that timed out may still have gone through at the bank, and the reply was lost. A blind retry then charges
the customer twice. The fix is a key made once per payment, outside the retry, that every try sends; the bank keeps
the first result for a key and returns it for the second try, which is why payment APIs take one (Stripe calls it
the Idempotency-Key header). In code, the gateway takes the key:
interface Gateway {
Receipt charge(String key, long amt);
}
Here are both pitfalls, with a bank whose first reply gets lost: the card is charged, but the caller sees a timeout.
/CodeVxDev
decorator
java OrderMatters.java
16:6:27
And the rest
- A wrapped gateway is not a
BankGateway.instanceofand casts to the concrete class fail on the outer wrapper. Code that needs the concrete type is a sign it should hold the interface instead. - Keep stacks shallow. Every wrapper adds a frame to each stack trace and one more place for a bug to hide. Three or four is plenty; past that, look for a pipeline or a framework feature.
- Don’t wrap what is always on. If every call must be logged and nothing ever runs without it, put it in the class: a wrapper is for extras that come and go.
Spot it in LLD interviews
When extras can be added in any combination, think Decorator:
| LLD question | The core object | The wrappers |
|---|---|---|
| Payment client | BankGateway | Logging, retry, metrics |
| Pizza or coffee order | A base item | Toppings and extras that add a price |
| Text editor | Plain text | Bold, italic, underline |
| File storage | A file stream | Compression, encryption, buffering |
| API client | An HTTP call | Auth header, metrics, tracing |
| Game character | A base character | Armour, power-ups that change stats |
The pizza is the one interviewers ask most, and its follow-up is worth preparing: why not a List<Topping> and a
sum? If toppings only add a price, a list is simpler, and you should say so. A decorator earns its place when each
extra changes what happens around the call, and the result still has to be a Pizza wherever a pizza is expected.
A notification service is a common example in tutorials, but a weak one here: its base has to be the email sender, so “SMS only” doesn’t fit, and the question is usually answered with a list of channels and an event, which is the Observer pattern.
When not to use it
If there is one fixed extra, a plain method call is enough. If the wrapper has to change the interface, it’s an adapter. And if it decides whether the call happens at all, it’s a proxy: that is the next episode.
/CodeVxDev
decorator
cat decorator.md
16:6:27
The interview trap
A debit card stands in for your bank account, but it checks your PIN and your limit before any money moves. Is that Decorator?
A. Yes, Decorator   B. No
Think about what a decorator is allowed to do with a call, and what this card does with a payment. Leave A or B as a
comment on the video; the next episode in this series answers it.