Notes
The problem
A shop sends events like order paid to partner systems through a webhook channel. Some partners need retries. Some need every request signed. Some need an audit log. With inheritance, you write a retrying webhook, a signed webhook, a signed retrying webhook, and so on. Three optional extras give eight combinations. Add a second kind of channel, like a message queue, and you have sixteen classes, all fixed at compile time.
- RetryingWebhookChannel
- SignedWebhookChannel
- AuditedWebhookChannel
- SignedRetryingWebhook...
- AuditedSignedRetrying...
- 3 optional extras: 2^3 = 8
- add a QueueChannel: 16
- and the choice is frozen
- at compile time
Why not flags?
Why not one class with boolean flags for retry, sign and audit? Because every new extra means editing the same class again, its constructor grows, its tests multiply, and extras for one channel cannot be reused by another. The order of the extras is also hard coded inside one method. We want each extra written once, in its own class, and combined freely at runtime.
class WebhookChannel {
boolean retry, sign, audit;
void send(String p) {
if (sign) p = sign(p);
if (audit) log(p);
if (retry) { loop... }
}
}
every new extra edits this
class and its tests The idea
The idea: write a wrapper that implements the same interface as the object it wraps. It does a little extra work before or after, and forwards the call inside. Formally, a decorator attaches extra responsibilities to an object dynamically, and is a flexible alternative to subclassing for extending behaviour. Because the wrapper has the same interface, the client cannot tell, and a wrapper can wrap another wrapper.
- a wrapper that implements the
- SAME interface as the object
- it wraps
- it does a little extra work,
- then forwards the call
- the client cannot tell a
- wrapped object from a bare one
- so wrappers can be stacked
The roles
The roles with our names. The component is the outbound channel interface. The concrete component is the webhook channel, which does the real sending. The abstract channel decorator implements the same interface and holds one outbound channel. The concrete decorators, retrying, signing and auditing, each extend the base and add exactly one behaviour. The event publisher is the client and knows only the interface.
Component
The component interface has a single method: send a payload. That small size matters, because every decorator must implement every method of the interface. The webhook channel does the real work, posting to the partner's address. In the demo it simulates a flaky partner that fails a set number of times with a five oh three error before it succeeds, so we can watch the retries happen.
interface OutboundChannel {
void send(String payload);
}
class WebhookChannel
implements OutboundChannel {
public void send(String payload) {
// POST to the partner URL
// demo: fails N times with 503
}
} Base decorator
The abstract decorator holds the wrapped channel in a final field, received in the constructor, and by default forwards every call to it. Concrete decorators then override only what they change. With a one method interface the base class saves little, but with a larger interface it saves every decorator from forwarding methods it does not care about. Notice the decorator depends on the interface, never on webhook channel.
abstract class ChannelDecorator
implements OutboundChannel {
protected final OutboundChannel inner;
public void send(String payload) {
inner.send(payload);
}
}
subclasses override only what
they change Concrete decorators
Each concrete decorator is short and does one thing. The retrying channel calls the inner channel in a loop and returns on the first success, or throws the last error after the maximum attempts. The signing channel computes a signature from a secret and the payload, then forwards the payload with the signature attached. The demo uses a toy hash. Real systems use an H M A C. The auditing channel records each success or failure.
// RetryingChannel
for (int a = 1; a <= max; a++) {
try { inner.send(p); return; }
catch (RuntimeException e) { last = e; }
}
throw last;
// SigningChannel
String sig = sign(secret, p);
inner.send(p + " sig=" + sig); Stacking
Now we combine them at runtime. For a partner that needs everything, wrap the webhook in a signing channel, wrap that in a retrying channel with three attempts, and wrap that in an auditing channel. The publisher receives the outermost object, typed only as an outbound channel. A partner that needs nothing gets the bare webhook. Three extras are three classes, and any combination is just a different nesting.
OutboundChannel ch =
new AuditingChannel(
new RetryingChannel(
new SigningChannel(
new WebhookChannel(url),
secret),
3),
auditLog);
new EventPublisher(ch); One call
Follow one call. The publisher calls send on what it thinks is just a channel. The auditing layer forwards to the retry layer. Attempt one goes through the signing layer, which attaches a signature, and reaches the webhook, which fails with five oh three. The retry layer tries again, the payload is signed again, and this time it succeeds. Control returns outward, and the audit layer records one success.
Order matters
The order of wrappers changes behaviour. With auditing on the outside, it sees one logical call and writes one entry. Move auditing inside the retry layer, and it sees every attempt: failed, failed, sent. Neither is wrong. One answers did the event get delivered, the other answers how flaky is this partner. Decide the order on purpose, build the stack in one place, like a factory, and test it.
- Audit(Retry(Sign(Webhook)))
- audit sees one call:
- 1 entry, "sent"
- Retry(Audit(Sign(Webhook)))
- audit sees every attempt:
- failed, failed, sent
- both are useful: decide
- on purpose, and test it
Java I/O streams
Java I/O is the textbook real example. File input stream is the concrete component that reads bytes. GZIP input stream wraps it and decompresses. Buffered input stream and data input stream are other decorators, and filter input stream is their base class, holding the wrapped stream. Input stream reader is different: it turns bytes into characters, so it is an adapter. Then buffered reader decorates the reader with buffering and read line.
new BufferedReader( // decorator
new InputStreamReader( // adapter
new GZIPInputStream( // decorator
new FileInputStream(f)), // source
UTF_8))
FilterInputStream: base decorator,
holds the wrapped stream "in"
BufferedInputStream, GZIPInputStream,
DataInputStream extend it More in the JDK
The collections class has more. Unmodifiable list returns a list that forwards reads and throws on writes. Synchronized list returns a list whose methods lock before forwarding. Checked list verifies the element type on every add. Each takes a list and returns a list with one behaviour added. The demo program below also builds a real compressing and decompressing stream stack in memory, so you can see the I/O decorators work.
Collections.unmodifiableList(list) // same List, writes throw Collections.synchronizedList(list) // same List, calls are locked Collections.checkedList(list, T.class) // same List, type checked on add the demo builds a real GZIP stack in memory: no files needed
When to use it
Use decorators when extras are optional and combine in many ways, when you cannot subclass because the class is final or comes from a library, and for cross cutting behaviour like retries, caching, logging, metrics and checks. There are costs. A deep stack of small objects is harder to debug. The wrapper is a different object, so identity checks and instanceof on the concrete class fail. And a big interface means many methods to forward.
- use when:
- • extras are optional and
- combine in many ways
- • you cannot or should not
- subclass (final classes)
- • cross-cutting: retry, cache,
- log, metrics, auth
- costs:
- • many small objects to debug
- • identity: wrapped != inner
- • big interfaces: lots to forward
Neighbours
Compare the wrapping patterns by intent. A decorator keeps the interface and adds behaviour, and the client chooses how to stack them. An adapter changes the interface to make something fit, and adds nothing. A proxy keeps the interface but controls access, for example lazy loading, permission checks or a remote call, and it often creates or owns the real object. A facade offers a new simple interface over many classes. A composite holds many children.
- Decorator: same interface,
- adds behaviour, stackable
- Adapter: different interface,
- translates, adds nothing
- Proxy: same interface,
- controls access; often owns
- or creates the real object
- Facade: new simple interface
- over many classes
- Composite: many children
In LLD interviews
In interviews, decorator fits whenever extras stack on a base: add on pricing where each extra adds to the cost, notification senders with retry and rate limit layers, loggers that add timestamps or levels, and repositories wrapped with caching or metrics. Common mistakes: a decorator that checks the concrete type of what it wraps, which breaks stacking, and forgetting to forward a method, which silently drops behaviour.
- add-on pricing: base item
- plus toppings or extras
- notifications: retry, rate
- limit, templating layers
- logger: timestamp, level and
- colour wrappers
- caching or metered repository
- mistakes:
- • decorator checks inner type
- • forgetting to forward a call
Say it like this
How to say it. Every channel implements the outbound channel interface. Retry, signing and auditing are decorators that wrap any channel, do one extra thing and forward the call. A factory builds the stack for each partner from configuration, so the order is chosen in one place and tested. Adding a new extra, like rate limiting, is one new class, and no existing class changes.
- "Every channel implements
- OutboundChannel. Retry, signing
- and audit are decorators that
- wrap any channel and forward.
- A factory builds the stack per
- partner, so the order is
- chosen in one place. New
- extras are one new class."