Patterns for structure · Chapter 11

Decorator pattern

Add behaviour to an object by wrapping it in another object with the same interface, and stack wrappers at run time. Java I/O streams, Python function decorators, and Decorator vs Proxy vs Adapter.

IntermediateInterview priority: High40 min
On this page
  1. The problem: a subclass for every combination
  2. The idea: wrap, add, pass inward
  3. Build it step by step
  4. Real decorators: Java I/O and Python's @ syntax
  5. Decorator, Proxy, Adapter, Facade: how they differ
  6. When not to use it
  7. In the interview
  8. Quiz

The problem: a subclass for every combination

A café sells espresso with optional extras: milk, caramel, whipped cream and an extra shot. The first design uses inheritance: Espresso, EspressoWithMilk, EspressoWithMilkAndCaramel, and so on.

One subclass per combination

  1. The Byte Café sells espresso, with extras: milk, caramel, whipped cream. With inheritance you need a subclass for every combination: EspressoWithMilk, EspressoWithMilkAndCaramel… Four extras already means sixteen classes per drink.

With 4 extras, each either present or not, that is 2⁴ = 16 classes per drink, and 5 drinks makes 80. A fifth extra doubles it again. Worse, "double caramel" needs yet another class, and the combination is fixed when the code is compiled: a customer can't add whipped cream at the till without a class that already has it.

The problem is that inheritance adds behaviour statically, to a whole class. We want to add it dynamically, to one object, and combine additions freely.

The idea: wrap, add, pass inward

A decorator is an object that implements the same interface as the thing it wraps, holds a reference to it, and adds its own behaviour before or after passing the call inward. Because the wrapper has the same interface, it can itself be wrapped. Whip(Caramel(Milk(Espresso))) is still a Drink.

Each layer wraps the next and adds its own part

  1. A decorator takes a different route. It’s an object that wraps another object with the same interface, adds its own bit, and passes the call inward. A Milk wraps the Espresso; Caramel wraps the Milk.
  2. Ask the outer cup for its cost. Whip asks Caramel, Caramel asks Milk, Milk asks Espresso: two dollars. Then each layer adds its own price on the way back out. That passing-inward is called delegation.
RoleIn this exampleResponsibility
Component (interface)DrinkWhat both plain objects and decorators offer: costCents(), description()
Concrete componentEspressoThe core object being decorated
Base decoratorAddOnHolds the wrapped Drink and forwards every call by default
Concrete decoratorsMilk, Caramel, WhipOverride the calls they change, then delegate to the inner object

Build it step by step

1. The component interface, shared by everything.

2. A concrete component, the plain drink.

3. A base decorator that stores the inner Drink and forwards each method unchanged. This saves each real decorator from re-writing every forwarding method.

4. Concrete decorators that override only what they change. The client builds the stack it wants at run time.

// 1. The component interface: plain drinks and add-ons both implement it
interface Drink {
    int costCents();          // money as whole cents, never double
    String description();
}

// 2. A concrete component: the thing being decorated
class Espresso implements Drink {
    public int costCents() { return 200; }
    public String description() { return "Espresso"; }
}

// 3. The base decorator: holds a Drink and forwards to it by default
abstract class AddOn implements Drink {
    protected final Drink inner;
    protected AddOn(Drink inner) { this.inner = inner; }
    public int costCents() { return inner.costCents(); }
    public String description() { return inner.description(); }
}

// 4. Concrete decorators: each adds its own bit around the inner call
class Milk extends AddOn {
    Milk(Drink inner) { super(inner); }
    @Override public int costCents() { return inner.costCents() + 50; }
    @Override public String description() { return inner.description() + ", milk"; }
}

class Caramel extends AddOn {
    Caramel(Drink inner) { super(inner); }
    @Override public int costCents() { return inner.costCents() + 60; }
    @Override public String description() { return inner.description() + ", caramel"; }
}

class Whip extends AddOn {
    Whip(Drink inner) { super(inner); }
    @Override public int costCents() { return inner.costCents() + 15; }
    @Override public String description() { return inner.description() + ", whip"; }
}

public class Main {
    public static void main(String[] args) {
        Drink order = new Whip(new Caramel(new Caramel(new Milk(new Espresso()))));
        System.out.println(order.description());   // Espresso, milk, caramel, caramel, whip
        System.out.printf("$%.2f%n", order.costCents() / 100.0);   // $3.85
    }
}

Count the classes: 1 drink + 1 base + 3 extras = 5, against 16 for the subclass version, and double caramel came for free. A new extra is one new class; a new drink is one new class. Neither touches existing code.

Order matters

Each decorator runs its code at its own layer, so the order of wrapping can change the result. For prices it doesn't (addition is commutative), but for most real decorators it does:

  • compress(encrypt(data)) barely compresses at all, because encrypted bytes look random. You want encrypt(compress(data)).
  • withAuth(withLogging(handler)) logs only requests that passed authentication; withLogging(withAuth(handler)) logs rejected ones too, which is usually what security teams want.
  • A retry wrapped inside a timeout gives all attempts one shared time budget; a timeout inside a retry gives each attempt its own.

Make the order explicit in one place (a factory or configuration), not scattered across callers.

Real decorators: Java I/O and Python's @ syntax

Java's java.io package is the textbook example. Reading lines from a gzipped text file stacks four objects:

try (BufferedReader in = new BufferedReader(          // decorator: adds buffering and readLine()
         new InputStreamReader(                       // adapter: bytes -> characters
             new GZIPInputStream(                     // decorator: decompresses, still an InputStream
                 new FileInputStream("app.log.gz")),  // concrete component: bytes from a file
             StandardCharsets.UTF_8))) {
    String line = in.readLine();
}

GZIPInputStream and BufferedInputStream both extend FilterInputStream, the JDK's base decorator, which holds an inner stream and forwards every call, just like AddOn. Notice the one layer that changes the interface, InputStreamReader: that one is an adapter, not a decorator.

Stacking decorators, in code you already use

  1. Because decorators stack, you can add the same one twice, double caramel, and decide at run time. Java’s file reading works this way: new BufferedReader(new FileReader(file)) wraps a reader to add buffering. Web frameworks wrap request handlers to add logging and security the same way.

Python function decorators (the @ syntax) apply the same idea to functions. A decorator takes a function and returns a new function with the same call signature that adds behaviour and calls the original inside. Strictly, the @ syntax is a language feature, not the GoF pattern, but the intent and the "wrap and delegate" shape are the same.

// Java has no @ syntax for this; the same idea is a higher-order function
static <T, R> Function<T, R> timed(String name, Function<T, R> fn) {
    return input -> {
        long start = System.nanoTime();
        try {
            return fn.apply(input);                   // pass the call inward
        } finally {
            System.out.printf("%s took %d µs%n", name, (System.nanoTime() - start) / 1000);
        }
    };
}

Function<String, Integer> price = timed("fetchPrice", sku -> 1999);
price.apply("A-42");

The stacked @ lines read top to bottom but apply bottom to top: retry wraps the function first, and timed wraps the result, so the timing includes every retry.

Other places you meet decorators: Collections.unmodifiableList and Collections.synchronizedList in Java, middleware in Express or Django, servlet filters, and HTTP client interceptors that add auth headers or retries.

Decorator, Proxy, Adapter, Facade: how they differ

DecoratorProxyAdapterFacade
InterfaceSame as the wrapped objectSame as the real objectDifferent (converts it)New and simpler
IntentAdd responsibilitiesControl access (lazy, guarded, cached, remote)Make an incompatible class fitSimplify a subsystem
Who builds the wrappingUsually the client, freely and in any combinationUsually a framework or factory; the client often doesn't knowWiring code, onceThe facade owns its parts
Stacks?Yes, that's the pointRarelyRarelyNo
Java I/O exampleBufferedReader(none)InputStreamReader(none)

Decorator and Proxy have identical class diagrams. The question to ask is: is the wrapper adding a feature the caller asked for, or deciding whether and when the real object gets called? Compare also with plain inheritance: subclassing adds behaviour to a whole class at compile time; a decorator adds it to one object at run time.

When not to use it

In the interview

Your turn: a notifier stack

A Notifier interface has one method, send(String user, String message). You have an EmailNotifier. Add, without editing it: (1) retry up to 3 times on IOException; (2) log every attempt and its outcome; (3) skip sending between 22:00 and 07:00 in the user's time zone. Sketch the classes and the line that builds the stack, and explain the order you chose.

Compare with our answer
interface Notifier { void send(String user, String message) throws IOException; }

class RetryingNotifier implements Notifier {
    private final Notifier inner; private final int times;
    RetryingNotifier(Notifier inner, int times) { this.inner = inner; this.times = times; }
    public void send(String user, String msg) throws IOException {
        for (int i = 1; ; i++) {
            try { inner.send(user, msg); return; }
            catch (IOException e) { if (i == times) throw e; }
        }
    }
}
// LoggingNotifier and QuietHoursNotifier follow the same shape.

Notifier n = new QuietHoursNotifier(
                 new RetryingNotifier(
                     new LoggingNotifier(new EmailNotifier()), 3), clock, timeZones);
class RetryingNotifier(Notifier):
    def __init__(self, inner: Notifier, times: int):
        self.inner, self.times = inner, times

    def send(self, user: str, msg: str) -> None:
        for attempt in range(1, self.times + 1):
            try:
                return self.inner.send(user, msg)
            except OSError:              # IOError is an alias of OSError
                if attempt == self.times:
                    raise

n = QuietHoursNotifier(
        RetryingNotifier(
            LoggingNotifier(EmailNotifier()), times=3), clock, time_zones)

A strong answer mentions: every wrapper implements Notifier and holds an inner Notifier · quiet hours outermost, so nothing is attempted or retried at night · logging inside retry, so each attempt is logged, not just the final result · the clock injected so quiet hours can be tested · what happens to messages skipped at night (dropped or queued).

Your turn: the requirement changes

The café now offers a "caramel lovers" promotion: caramel is free if the drink has two or more caramels. With pure decorators, each Caramel only sees the drink inside it. How would you implement the promotion, and what does that tell you about the pattern's limits?

Compare with our answer

A strong answer mentions: a decorator cannot easily see layers outside it or count its siblings · options include an outer Promotion decorator that inspects the description or asks the stack for its extras (an extras() method on Drink), or computing discounts separately at checkout · moving pricing rules out of the decorators into a pricing step (a strategy) once rules depend on the whole order · keeping decorators for independent, local additions.

Decorator on one page
  • Intent: add responsibilities to one object at run time by wrapping it in an object with the same interface.
  • Roles: component interface · concrete component · base decorator (forwards everything) · concrete decorators.
  • Wins: no subclass explosion (n extras, not 2ⁿ classes); combine and repeat freely; each feature is one small class.
  • Order matters: compress then encrypt; log outside auth; timeout around retries.
  • Real ones: BufferedReader, GZIPInputStream (FilterInputStream), Collections.unmodifiableList, middleware, Python @functools.wraps decorators.
  • Not Proxy: same diagram, but proxy controls access; decorator adds features. Not Adapter: adapters change the interface.
  • Limits: identity and instanceof break; self-calls bypass the wrapper; big interfaces need forwarding.
Interactive labPractise it: build drinks from stacked extrasOpens in the ByteAtlas lab. Your progress is saved in this browser.
Check what stuck

1. A pizza shop has 6 toppings that customers combine freely, including double portions. Which design keeps the class count small and allows any combination?

2. In new BufferedReader(new InputStreamReader(new FileInputStream(f))), which layer is not a decorator?

3. A web app wraps its handler as withAuth(withLogging(handler)). Security complains that rejected login attempts never appear in the logs. Why?

4. A CachingRepository decorator wraps a Repository. Inside the real repository, findAll() calls this.findById(id) for each id. Why does findAll() get no benefit from the cache?

5. What is the key difference between Decorator and Proxy, given that their class diagrams are identical?

6. An interface you decorate has 25 methods and gains new ones every release. What reduces the risk of decorators silently breaking?

Score 60% or more and the lesson is marked complete.

Passing the quiz also marks it complete. Progress is saved in this browser only.