Decorator Pattern

November 25, 202610 minutes

Seven classes for three features, or three small wrappers? Learn how the Decorator pattern adds one job at a time through the same interface, with plug-in adapters, java.io streams, diagrams, Java code and a narrated video.

Your weather app fetches the forecast from the network; one class does the work, the HttpFetcher. Then you want logging. Then retries, for when the network blips. Then a cache. Some calls need all three, and some need only the cache. Write one subclass for each combination, and you need seven classes. Add a fourth feature, and it’s fifteen. There’s a way to write each feature once and combine them however you like: the Decorator pattern.

Prefer to watch? The narrated video above covers the same lesson (about 9 minutes). The article follows it section by section, with diagrams and a little extra depth.

Seven classes for three features

Three optional features that combine freely give 2³ − 1 = 7 combinations besides the plain fetcher; a fourth feature doubles that to 15. One subclass per combination doesn’t scale:

HttpFetcher with three optional features, logging, retry and cache, gives seven subclasses: LoggingHttpFetcher, RetryingHttpFetcher, CachingHttpFetcher, LoggingRetryingHttpFetcher, LoggingCachingHttpFetcher, RetryingCachingHttpFetcher and LoggingRetryingCachingHttpFetcher; adding auth makes fifteen. HttpFetcher with three optional features, logging, retry and cache, gives seven subclasses: LoggingHttpFetcher, RetryingHttpFetcher, CachingHttpFetcher, LoggingRetryingHttpFetcher, LoggingCachingHttpFetcher, RetryingCachingHttpFetcher and LoggingRetryingCachingHttpFetcher; adding auth makes fifteen.
Three features, seven classes. Four features, fifteen.

A lamp, a timer, a surge protector

Start with something simpler: a lamp, plugged into the wall. You’d like it to switch on by itself at seven every evening. You don’t buy a new lamp with a timer built in. You plug a timer into the wall, and the lamp into the timer.

The trick is the timer’s shape: it has a plug on the back and a socket on the front. The wall sees a plug, and the lamp sees a socket. So you can keep going: a surge protector goes in too, and neither the wall nor the lamp can tell how many adapters sit in between.

In pattern words, the lamp is the component, the thing you want to extend. Each adapter is a decorator: it has the same shape, and adds one job.

The wall socket feeds a surge protector, which feeds a timer, which feeds the lamp; each adapter has a plug on the back and a socket on the front, so the lamp is the component and the adapters are decorators. The wall socket feeds a surge protector, which feeds a timer, which feeds the lamp; each adapter has a plug on the back and a socket on the front, so the lamp is the component and the adapters are decorators.
Same plug, same socket: adapters stack, and the lamp never changes.

The obvious ways

Back to code. The first thing most of us reach for is a subclass: LoggingHttpFetcher extends HttpFetcher, logs the address, and calls super:

class LoggingHttpFetcher extends HttpFetcher {
    public String get(String url) {
        log("GET " + url);
        return super.get(url);
    }
}

It’s short and clear. For one feature that never changes, it’s the right answer.

The second idea avoids extra classes altogether: one fetcher with a flag for each feature. Logging on, retry off, cache on:

class HttpFetcher {
    private final boolean logging, retry, cache;
    private final Map<String, String> cached = new HashMap<>();

    HttpFetcher(boolean logging, boolean retry, boolean cache) {
        this.logging = logging; this.retry = retry; this.cache = cache;
    }

    String get(String url) {
        if (logging) log("GET " + url);
        if (cache && cached.containsKey(url)) return cached.get(url);
        String body = retry ? sendWithRetry(url) : send(url);
        if (cache) cached.put(url, body);
        return body;
    }
}

One class, everything in one place, and no explosion of subclasses. That’s also a fair choice, while the list of features stays short.

Why it breaks

Subclasses break on combinations. Every mix of features needs its own class, written in advance: three features make seven, and four make fifteen. And if the mix comes from a config file at run time, the class you need has to exist already.

Flags break differently. Someone asks to log every retry attempt, not only the call. But logging runs first, fixed in code, outside the retry. Then another team needs an auth header: one more flag, one more line, and one more edit to a class that every feature now shares.

Two requests hit the flags version: log every retry attempt runs into the fixed order of the if statements, and add an auth header forces another flag and another line in the same get method, so every feature is tangled in one method. Two requests hit the flags version: log every retry attempt runs into the fixed order of the if statements, and add an auth header forces another flag and another line in the same get method, so every feature is tangled in one method.
Every feature edits the same class, and the order is baked in.

It’s the lamp shop again: a different lamp for every mix of timer and surge protector, or one lamp whose base keeps growing switches.

The key insight: same plug, same socket

The timer showed the way. Make each feature an object with the same interface as the fetcher, that also holds a fetcher inside. It does its one job, then passes the call on. From outside, it looks exactly like any other fetcher, so wrappers stack, in any order, and the caller can’t tell how many there are.

The Gang of Four describe it as adding responsibilities to one object at run time, a flexible alternative to subclassing. They also call it a wrapper.

A Fetcher wrapper implements Fetcher and holds an inner Fetcher; calls come in through the wrapper's get, the wrapper does its one job, and passes the call to the inner fetcher, which can be HttpFetcher or another wrapper. A Fetcher wrapper implements Fetcher and holds an inner Fetcher; calls come in through the wrapper's get, the wrapper does its one job, and passes the call to the inner fetcher, which can be HttpFetcher or another wrapper.
Is a Fetcher, has a Fetcher: that's the whole trick.

Same interface, one more job.

Building it

Four pieces. First, the interface every layer shares: Fetcher, with a single get method (the plug shape). Second, the real worker: the HttpFetcher, which makes the network call (the lamp).

interface Fetcher {
    String get(String url);
}
class HttpFetcher implements Fetcher {
    public String get(String url) {
        return send(url);          // the real network call
    }
}

Third, a decorator base. It implements Fetcher, so it has the same plug. It holds an inner fetcher, which is the socket. And by default, get passes straight through:

abstract class FetcherDecorator implements Fetcher {
    protected final Fetcher inner;

    FetcherDecorator(Fetcher inner) { this.inner = inner; }

    public String get(String url) { return inner.get(url); }
}

Fourth, the features. LoggingFetcher logs the address, then calls the inner fetcher. That’s its whole job:

class LoggingFetcher extends FetcherDecorator {
    LoggingFetcher(Fetcher inner) { super(inner); }

    public String get(String url) {
        log("GET " + url);
        return inner.get(url);
    }
}

RetryingFetcher tries the inner call up to three times. CachingFetcher remembers each answer, and only asks the inner fetcher on a miss (computeIfAbsent stores nothing if the call throws):

class RetryingFetcher extends FetcherDecorator {
    RetryingFetcher(Fetcher inner) { super(inner); }

    public String get(String url) {
        for (int attempt = 1; ; attempt++) {
            try {
                return inner.get(url);
            } catch (UncheckedIOException e) {
                if (attempt == 3) throw e;
            }
        }
    }
}

class CachingFetcher extends FetcherDecorator {
    private final Map<String, String> cache = new HashMap<>();

    CachingFetcher(Fetcher inner) { super(inner); }

    public String get(String url) {
        return cache.computeIfAbsent(url, inner::get);
    }

    void clear() { cache.clear(); }
}

Now the client puts them together, from the inside out: HTTP, then retrying, then caching, and logging on the outside:

Fetcher fetcher =
    new LoggingFetcher(
        new CachingFetcher(
            new RetryingFetcher(
                new HttpFetcher())));

String forecast = fetcher.get("/forecast");

Watch one call. It’s logged, the cache misses, the network times out once, the retry succeeds, and “sunny” travels back out through every layer. Call it again: it’s logged, the cache hits, and the network is never touched. Nothing in the HttpFetcher changed to make any of this happen.

Sequence of the first call: LoggingFetcher.get logs and calls CachingFetcher.get; the cache misses and calls RetryingFetcher.get; the first HttpFetcher call times out, the second returns sunny; sunny is cached and returned outward. Second call: logging, then a cache hit returns sunny without touching the network. Sequence of the first call: LoggingFetcher.get logs and calls CachingFetcher.get; the cache misses and calls RetryingFetcher.get; the first HttpFetcher call times out, the second returns sunny; sunny is cached and returned outward. Second call: logging, then a cache hit returns sunny without touching the network.
A call travels in through every layer; the answer travels back out.

Anatomy: four roles and a stacking order

The Gang of Four gave the four roles names. The interface is the component. The real worker is the concrete component. The base that holds one and passes calls on is the decorator. And each one-job layer is a concrete decorator.

Class diagram: Fetcher is an interface with get(url); HttpFetcher implements it; the abstract FetcherDecorator implements it and holds an inner Fetcher; LoggingFetcher, RetryingFetcher and CachingFetcher extend FetcherDecorator. Class diagram: Fetcher is an interface with get(url); HttpFetcher implements it; the abstract FetcherDecorator implements it and holds an inner Fetcher; LoggingFetcher, RetryingFetcher and CachingFetcher extend FetcherDecorator.
Component, concrete component, decorator, concrete decorators.

Why a base class? With a one-method interface, it saves little. But with ten methods, each decorator would forward all ten by hand. The base forwards them once, and each decorator overrides only what it changes.

And the nesting is the call order. On the way in, the outermost layer goes first. On the way back out, it goes last.

Two traps: order and identity

Order is the first trap. Here are two wirings with the same two layers, and a network that fails twice before it works:

Fetcher once  = new LoggingFetcher(new RetryingFetcher(http));  // logs once
Fetcher every = new RetryingFetcher(new LoggingFetcher(http));  // logs every attempt

With logging outside, the log shows one line: the call. With retrying outside, logging sits inside the loop, and the log shows all three attempts. Neither one is wrong: they answer different questions. So pick the order on purpose.

Left: logging wraps retry wraps http, so one call is logged once even though http fails twice. Right: retry wraps logging wraps http, so each of the three attempts passes through logging and the log has three lines. Left: logging wraps retry wraps http, so one call is logged once even though http fails twice. Right: retry wraps logging wraps http, so each of the three attempts passes through logging and the log has three lines.
Same two layers, different order, different log.

The outside runs first.

Identity is the second trap. Wrap the cache in logging, and the object you hold is the logging fetcher. instanceof CachingFetcher is false. == is false. (The default equals is identity, so it’s false too; the Gang of Four warn not to rely on object identity with decorators.)

CachingFetcher cache = new CachingFetcher(new HttpFetcher());
Fetcher fetcher = new LoggingFetcher(cache);

boolean sameType   = fetcher instanceof CachingFetcher;  // false
boolean sameObject = fetcher == cache;                    // false

cache.clear();  // keep a handle to the layer you need

It’s the lamp again: ask what’s plugged into the wall, and the answer is the surge protector. Code that checks types breaks the moment someone adds a layer. If you need one layer, say the cache, so you can clear it, keep your own reference to that layer.

A realistic example: Java’s input streams

You’ve typed decorators already, maybe without noticing. Here’s how Java reads a compressed log file:

InputStream in =
    new BufferedInputStream(
        new GZIPInputStream(
            new FileInputStream("events.log.gz")));

A FileInputStream reads the raw bytes. A GZIPInputStream wraps it and decompresses. A BufferedInputStream wraps that, and reads in big chunks. Every one of them is an InputStream holding an InputStream. Their shared base, FilterInputStream, is a decorator base built into Java: its Javadoc says it “wraps some other input stream, which it uses as its basic source of data, possibly transforming the data along the way or providing additional functionality.”

Class diagram: InputStream is the component; FileInputStream extends it; FilterInputStream extends it and holds an inner InputStream; BufferedInputStream, DataInputStream, CipherInputStream and InflaterInputStream extend FilterInputStream, and GZIPInputStream extends InflaterInputStream. Class diagram: InputStream is the component; FileInputStream extends it; FilterInputStream extends it and holds an inner InputStream; BufferedInputStream, DataInputStream, CipherInputStream and InflaterInputStream extend FilterInputStream, and GZIPInputStream extends InflaterInputStream.
java.io: the same four roles, shipped with the JDK.

One wrapper nearby is not a decorator. An InputStreamReader takes bytes and gives you characters: it changes the interface, so it’s an adapter. The same idea lives in java.util.Collections: unmodifiableList(list) hands back a List that wraps yours and refuses changes, same interface, one more job.

Decorator vs its neighbours

Three neighbours get confused with decorator.

Inheritance. A subclass changes a whole class, before the program runs. A decorator changes one object, while it runs, and it stacks.

Proxy. It has exactly the same shape: the same interface, holding the real object. But its job is control: it loads the object lazily, checks permissions, or talks to a remote server. Think of a safety cover on a socket: it decides who gets power.

A decorator adds. A proxy guards.

Strategy. It swaps something inside the object, like changing the lamp’s bulb. The Gang of Four describe it as skin versus guts: a decorator changes the skin, and a strategy changes the guts. (See the Strategy pattern.)

DecoratorProxyStrategySubclass
Same interface as the object?yesyesno (a separate role)yes (it is the class)
Purposeadd a jobcontrol accessswap the algorithm insidespecialise a whole class
Chosenby the client, per objectusually hidden from the clientby the client, per objectat compile time
Stacks?yes, any orderrarelyone at a timeonly by more subclasses

And compared with the Chain of Responsibility: a decorator always passes the call on; a chain decides who stops.

When to use it (and when not to)

Use decorators when optional features combine freely, per object, maybe chosen at run time. And when you can’t edit the class, because it belongs to a library or another team.

Skip them for one fixed combination: if every fetcher is always logged, log in one place and move on. Skip them when the feature needs a new method: the outer layer only shows the interface, so callers can’t reach it. And watch the depth: ten thin layers make a stack trace that’s hard to read, and an interface with thirty methods makes every wrapper heavy (the Gang of Four’s “lots of little objects”).

Decision flowchart: if the feature needs a new method callers must reach, don't decorate; if the combination is always the same, build it once; if the interface is very wide, consider another design; otherwise use decorators and keep the stack shallow. Decision flowchart: if the feature needs a new method callers must reach, don't decorate; if the combination is always the same, build it once; if the interface is very wide, consider another design; otherwise use decorators and keep the stack shallow.
When decorators pay for themselves.

Recap

Back to the weather app: seven classes became three small wrappers around one HttpFetcher, stacked in whatever order each call needs.

  • Each wrapper has the same interface and holds one of it.
  • It does one job, then passes the call on.
  • The outside runs first.
  • The object you hold is the outer layer: don’t rely on identity or type checks.
  • A decorator adds, a proxy guards; a decorator changes the skin, a strategy the guts.
Recap chain: same interface, holds one, one job, pass it on. Recap chain: same interface, holds one, one job, pass it on.
Seven classes became three small wrappers.

Same interface, one more job.

Related patterns: the Observer pattern also hides receivers behind one small interface, but broadcasts one change to many listeners instead of wrapping one object; the Command pattern turns a call into an object.