LOW-LEVEL DESIGN · STRUCTURAL PATTERNS · STRUCTURAL · 30 OF 48

Decorator Design Pattern in Java: Stackable Wrappers, Java I/O

The Decorator pattern explained with a webhook sender that gains retries, request signing and audit logging by wrapping instead of subclassing: the subclass explosion it prevents, component and decorator roles, stacking, why the order of wrappers matters, Java I/O streams as a real example, costs, and Decorator vs Adapter, Proxy, Facade and Composite.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
1 / 18

Press play to hear the narration, or step through at your own pace. The Java example is below.

Java example

One file, Java 17, 202 lines, with a small main() demo. Save it as WebhookDecoratorDemo.java, then run javac WebhookDecoratorDemo.java && java WebhookDecoratorDemo.

// Decorator pattern: add retry, signing and auditing to any outbound channel by wrapping it.
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class WebhookDecoratorDemo {

    public static void main(String[] args) throws IOException {
        System.out.println("-- Before: a subclass for each combination --");
        new RetryingWebhookChannel(1).send("order.paid#1");

        System.out.println("-- After: Audit(Retry(Sign(Webhook))) --");
        List<String> auditLog = new ArrayList<>();
        OutboundChannel outer = new AuditingChannel(
                new RetryingChannel(new SigningChannel(new WebhookChannel(2), "k3y"), 3), auditLog);
        new EventPublisher(outer).publish("order.paid#2");
        System.out.println("audit outside retry: " + auditLog);

        System.out.println("-- Same wrappers, other order: Retry(Audit(Sign(Webhook))) --");
        auditLog.clear();
        OutboundChannel inner = new RetryingChannel(
                new AuditingChannel(new SigningChannel(new WebhookChannel(2), "k3y"), auditLog), 3);
        new EventPublisher(inner).publish("order.paid#3");
        System.out.println("audit inside retry: " + auditLog);

        System.out.println("-- A partner that needs no extras --");
        new EventPublisher(new WebhookChannel(0)).publish("order.paid#4");

        System.out.println("-- The same idea in java.io --");
        javaIoDemo();
    }

    /** Builds a real decorator stack: compress into memory, then read it back line by line. */
    private static void javaIoDemo() throws IOException {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        try (OutputStream out = new GZIPOutputStream(bytes)) {           // decorator: compresses
            out.write("line one\nline two\n".getBytes(StandardCharsets.UTF_8));
        }
        try (BufferedReader reader = new BufferedReader(                  // decorator: buffering, readLine
                new InputStreamReader(                                     // adapter: bytes to chars
                        new GZIPInputStream(                               // decorator: decompresses
                                new ByteArrayInputStream(bytes.toByteArray())), // concrete source
                        StandardCharsets.UTF_8))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println("read: " + line);
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Component and concrete component.
// ---------------------------------------------------------------------------
interface OutboundChannel {
    void send(String payload);
}

/** Does the real sending. The demo fails a set number of times to simulate a flaky partner. */
class WebhookChannel implements OutboundChannel {
    private int failuresLeft;

    WebhookChannel(int failuresBeforeSuccess) {
        this.failuresLeft = failuresBeforeSuccess;
    }

    @Override
    public void send(String payload) {
        if (failuresLeft > 0) {
            failuresLeft--;
            System.out.println("  POST failed with 503");
            throw new IllegalStateException("partner returned 503");
        }
        System.out.println("  POST " + payload);
    }
}

// ---------------------------------------------------------------------------
// The problem: one subclass per combination of extras (2^3 = 8 per channel type).
// ---------------------------------------------------------------------------
class RetryingWebhookChannel extends WebhookChannel {
    RetryingWebhookChannel(int failuresBeforeSuccess) {
        super(failuresBeforeSuccess);
    }

    @Override
    public void send(String payload) {
        for (int attempt = 1; ; attempt++) {
            try {
                super.send(payload);
                return;
            } catch (IllegalStateException e) {
                if (attempt == 3) {
                    throw e;
                }
            }
        }
    }
}
// ...then SignedRetryingWebhookChannel, AuditedSignedRetryingWebhookChannel, and so on.

// ---------------------------------------------------------------------------
// Base decorator: same interface, holds ONE wrapped channel, forwards by default.
// ---------------------------------------------------------------------------
abstract class ChannelDecorator implements OutboundChannel {
    protected final OutboundChannel inner;

    protected ChannelDecorator(OutboundChannel inner) {
        this.inner = Objects.requireNonNull(inner);
    }

    @Override
    public void send(String payload) {
        inner.send(payload);
    }
}

class RetryingChannel extends ChannelDecorator {
    private final int maxAttempts;

    RetryingChannel(OutboundChannel inner, int maxAttempts) {
        super(inner);
        if (maxAttempts < 1) {
            throw new IllegalArgumentException("maxAttempts must be at least 1");
        }
        this.maxAttempts = maxAttempts;
    }

    @Override
    public void send(String payload) {
        RuntimeException last = null;
        for (int attempt = 1; attempt <= maxAttempts; attempt++) {
            try {
                inner.send(payload);
                return;
            } catch (RuntimeException e) {
                last = e;
                System.out.println("  retry layer: attempt " + attempt + " failed");
            }
        }
        throw last;
    }
}

class SigningChannel extends ChannelDecorator {
    private final String secret;

    SigningChannel(OutboundChannel inner, String secret) {
        super(inner);
        this.secret = secret;
    }

    @Override
    public void send(String payload) {
        // Toy signature to keep the demo short. Real systems use an HMAC such as HmacSHA256.
        String signature = Integer.toHexString((secret + payload).hashCode());
        inner.send(payload + " sig=" + signature);
    }
}

class AuditingChannel extends ChannelDecorator {
    private final List<String> log;

    AuditingChannel(OutboundChannel inner, List<String> log) {
        super(inner);
        this.log = log;
    }

    @Override
    public void send(String payload) {
        try {
            inner.send(payload);
            log.add("sent");
        } catch (RuntimeException e) {
            log.add("failed");
            throw e;
        }
    }
}

// Client: knows only the interface, so it cannot tell how many wrappers there are.
class EventPublisher {
    private final OutboundChannel channel;

    EventPublisher(OutboundChannel channel) {
        this.channel = channel;
    }

    void publish(String event) {
        channel.send(event);
        System.out.println("published " + event);
    }
}

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.

Subclass for each combo
  • 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.

The flag version
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.

Decorator in one line
  • 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.

The real work
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.

ChannelDecorator
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.

Two decorators
// 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.

Wiring for one partner
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 outside vs inside
  • 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.

Reading a gzipped text
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.

Other wrappers
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 / avoid
  • 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.

Wrappers compared
  • 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.

Where it shows up
  • 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.

In the interview
  • "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."

Interview questions

What problem does the Decorator pattern solve?

It adds optional behaviour to individual objects at runtime without creating a subclass for every combination. Each extra is a wrapper with the same interface that does its work and forwards the call, and wrappers can be stacked in any order.

Why prefer decorators over inheritance for optional features?

With inheritance, n optional features can need up to 2 to the power n subclasses per base class, and the choice is fixed at compile time. Decorators need one class per feature, combine freely at runtime, and work even when the base class is final.

How is the Decorator pattern used in Java I/O?

Streams wrap other streams. FilterInputStream is the base decorator holding the wrapped stream, and BufferedInputStream, DataInputStream and GZIPInputStream add buffering, typed reads and decompression. BufferedReader decorates a Reader; InputStreamReader, which converts bytes to characters, is an adapter rather than a decorator.

What is the difference between Decorator and Proxy?

They have the same structure: a wrapper with the same interface. A decorator adds behaviour and is usually stacked by the client. A proxy controls access to the real object, for example lazily creating it, checking permissions or calling it remotely, and often manages its lifecycle.

What is the difference between Decorator and Adapter?

A decorator keeps the same interface and adds behaviour. An adapter exposes a different interface from the object it wraps so that it fits a client, and does not add new behaviour.

Does the order of decorators matter?

Yes. Each wrapper only sees what passes through its layer. For example, an audit decorator outside a retry decorator logs one entry per call, while inside it logs every attempt. Build stacks in one place, such as a factory, and test the order.

What are the drawbacks of the Decorator pattern?

Many small objects make debugging and stack traces harder, the wrapper is not the same object as the inner one so identity and concrete-type checks fail, and large interfaces force every decorator to forward many methods unless a base decorator does it.

Where would you use Decorator in an LLD interview?

For add-on pricing where extras add cost to a base item, for notification or HTTP clients wrapped with retry, rate limiting and logging, for loggers that add timestamps or levels, and for repositories wrapped with caching or metrics.