# Decorator PatternSeven 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**.

{{< lesson-video youtube="qTDUaNxK9eo" title="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:

```mermaid {alt="HttpFetcher with three optional features, logging, retry and cache, gives seven subclasses: LoggingHttpFetcher, RetryingHttpFetcher, CachingHttpFetcher, LoggingRetryingHttpFetcher, LoggingCachingHttpFetcher, RetryingCachingHttpFetcher and LoggingRetryingCachingHttpFetcher; adding auth makes fifteen." caption="Three features, seven classes. Four features, fifteen."}
flowchart LR
  H["HttpFetcher"] --> A["Logging…"]
  H --> B["Retrying…"]
  H --> C["Caching…"]
  H --> D["LoggingRetrying…"]
  H --> E["LoggingCaching…"]
  H --> F["RetryingCaching…"]
  H --> G["LoggingRetryingCaching…"]
  G -.->|"+ auth"| X["15 classes"]
  class H c6
  class A,B,C,D,E,F,G warn
  class X bad
```

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

```mermaid {alt="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." caption="Same plug, same socket: adapters stack, and the lamp never changes."}
flowchart LR
  W["wall"] --> S["surge protector<br/>(decorator)"] --> T["timer<br/>(decorator)"] --> L["lamp<br/>(component)"]
  class L c6
  class S,T c1
```

## 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`:

```java
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:

```java
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.

```mermaid {alt="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." caption="Every feature edits the same class, and the order is baked in."}
flowchart LR
  R1["log every attempt"] --> G["HttpFetcher.get()<br/>logging → cache → retry<br/>(order fixed in code)"]
  R2["add auth"] --> G
  R3["next feature…"] --> G
  class R1,R2,R3 warn
  class G bad
```

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.

```mermaid {alt="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." caption="Is a Fetcher, has a Fetcher: that's the whole trick."}
flowchart TD
  C["caller"] -->|"get(url)"| W["wrapper<br/>is a Fetcher"]
  W -->|"one job, then get(url)"| I["inner<br/>has a Fetcher"]
  I -.-> H["HttpFetcher<br/>or another wrapper"]
  class W c1
  class H c6
```

> **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).

```java
interface Fetcher {
    String get(String url);
}
```

```java
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:

```java
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:

```java
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):

```java
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:

```java
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.**

```mermaid {alt="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." caption="A call travels in through every layer; the answer travels back out."}
sequenceDiagram
  participant L as Logging
  participant K as Caching
  participant R as Retrying
  participant H as Http
  Note over L: get("/forecast"), log it
  L->>K: get
  Note over K: miss
  K->>R: get
  R->>H: attempt 1
  H--xR: timeout
  R->>H: attempt 2
  H-->>R: "sunny"
  R-->>K: "sunny" (cached)
  K-->>L: "sunny"
  Note over L: returns "sunny"
  Note over L: get("/forecast") again
  L->>K: get
  K-->>L: hit: "sunny"
```

## 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**.

```mermaid {alt="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." caption="Component, concrete component, decorator, concrete decorators."}
classDiagram
  class Fetcher {
    <<interface>>
    +get(String url) String
  }
  class HttpFetcher {
    +get(String url) String
  }
  class FetcherDecorator {
    <<abstract>>
    #Fetcher inner
    +get(String url) String
  }
  Fetcher <|.. HttpFetcher
  Fetcher <|.. FetcherDecorator
  FetcherDecorator o--> Fetcher : inner
  FetcherDecorator <|-- LoggingFetcher
  FetcherDecorator <|-- RetryingFetcher
  FetcherDecorator <|-- CachingFetcher
  note for FetcherDecorator "forwards by default; subclasses override what they change"
```

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:

```java
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.

```mermaid {alt="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." caption="Same two layers, different order, different log."}
flowchart LR
  subgraph once["Logging outside: 1 log line"]
    direction TB
    L1["LoggingFetcher"] --> R1["RetryingFetcher"] --> H1["http ✗ ✗ ✓"]
  end
  subgraph every["Retrying outside: 3 log lines"]
    direction TB
    R2["RetryingFetcher"] --> L2["LoggingFetcher"] --> H2["http ✗ ✗ ✓"]
  end
  once ~~~ every
  class L1,L2 c5
  class R1,R2 c4
  class H1,H2 c6
```

> **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.)

```java
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:

```java
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."

```mermaid {alt="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." caption="java.io: the same four roles, shipped with the JDK."}
classDiagram
  class InputStream {
    <<abstract>>
    +read() int
  }
  InputStream <|-- FileInputStream
  InputStream <|-- FilterInputStream
  FilterInputStream o--> InputStream : in
  FilterInputStream <|-- BufferedInputStream
  FilterInputStream <|-- DataInputStream
  FilterInputStream <|-- CipherInputStream
  FilterInputStream <|-- InflaterInputStream
  InflaterInputStream <|-- GZIPInputStream
```

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](/patterns/proxy-pattern/).** 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](/patterns/strategy-pattern/).)

| | Decorator | Proxy | Strategy | Subclass |
|---|---|---|---|---|
| Same interface as the object? | yes | yes | no (a separate role) | yes (it *is* the class) |
| Purpose | add a job | control access | swap the algorithm inside | specialise a whole class |
| Chosen | by the client, per object | usually hidden from the client | by the client, per object | at compile time |
| Stacks? | yes, any order | rarely | one at a time | only by more subclasses |

And compared with the [Chain of Responsibility](/patterns/chain-of-responsibility-pattern/):
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").

```mermaid {alt="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." caption="When decorators pay for themselves."}
flowchart TD
  A{"Does the feature need a<br/>new method callers must reach?"} -->|yes| N["not a decorator"]
  A -->|no| B{"Is the combination<br/>always the same?"}
  B -->|yes| O["write it once"]
  B -->|no| C{"Is the interface<br/>very wide?"}
  C -->|yes| W["heavy wrappers:<br/>reconsider"]
  C -->|no| D["Decorator<br/>(keep the stack shallow)"]
  class N,O,W muted
  class D good
```

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

```mermaid {alt="Recap chain: same interface, holds one, one job, pass it on." caption="Seven classes became three small wrappers."}
flowchart LR
  A["same interface"] --> B["holds one"] --> C["one job"] --> D["pass it on"]
  class A c1
  class D good
```

> **Same interface, one more job.**

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