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.
On this page
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
- 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
- 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.
- 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.
| Role | In this example | Responsibility |
|---|---|---|
| Component (interface) | Drink | What both plain objects and decorators offer: costCents(), description() |
| Concrete component | Espresso | The core object being decorated |
| Base decorator | AddOn | Holds the wrapped Drink and forwards every call by default |
| Concrete decorators | Milk, Caramel, Whip | Override 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
}
}from abc import ABC, abstractmethod
class Drink(ABC): # 1. the component interface
@abstractmethod
def cost_cents(self) -> int: ...
@abstractmethod
def description(self) -> str: ...
class Espresso(Drink): # 2. a concrete component
def cost_cents(self) -> int:
return 200
def description(self) -> str:
return "Espresso"
class AddOn(Drink): # 3. the base decorator: forwards by default
def __init__(self, inner: Drink):
self.inner = inner
def cost_cents(self) -> int:
return self.inner.cost_cents()
def description(self) -> str:
return self.inner.description()
class Milk(AddOn): # 4. concrete decorators
def cost_cents(self) -> int:
return self.inner.cost_cents() + 50
def description(self) -> str:
return self.inner.description() + ", milk"
class Caramel(AddOn):
def cost_cents(self) -> int:
return self.inner.cost_cents() + 60
def description(self) -> str:
return self.inner.description() + ", caramel"
class Whip(AddOn):
def cost_cents(self) -> int:
return self.inner.cost_cents() + 15
def description(self) -> str:
return self.inner.description() + ", whip"
order = Whip(Caramel(Caramel(Milk(Espresso()))))
print(order.description()) # Espresso, milk, caramel, caramel, whip
print(f"${order.cost_cents() / 100:.2f}") # $3.85Count 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 wantencrypt(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
retrywrapped inside atimeoutgives all attempts one shared time budget; atimeoutinside aretrygives 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
- 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");import functools, time
def timed(fn):
@functools.wraps(fn) # keep fn's name and docstring
def wrapper(*args, **kwargs):
start = time.perf_counter()
try:
return fn(*args, **kwargs) # pass the call inward
finally:
ms = (time.perf_counter() - start) * 1000
print(f"{fn.__name__} took {ms:.1f} ms")
return wrapper
def retry(times: int):
def decorate(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
for attempt in range(1, times + 1):
try:
return fn(*args, **kwargs)
except ConnectionError:
if attempt == times:
raise
return wrapper
return decorate
@timed
@retry(times=3) # same as: fetch_price = timed(retry(times=3)(fetch_price))
def fetch_price(sku: str) -> int:
return 1999The 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
| Decorator | Proxy | Adapter | Facade | |
|---|---|---|---|---|
| Interface | Same as the wrapped object | Same as the real object | Different (converts it) | New and simpler |
| Intent | Add responsibilities | Control access (lazy, guarded, cached, remote) | Make an incompatible class fit | Simplify a subsystem |
| Who builds the wrapping | Usually the client, freely and in any combination | Usually a framework or factory; the client often doesn't know | Wiring code, once | The facade owns its parts |
| Stacks? | Yes, that's the point | Rarely | Rarely | No |
| Java I/O example | BufferedReader | (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
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).
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.
- 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.wrapsdecorators. - Not Proxy: same diagram, but proxy controls access; decorator adds features. Not Adapter: adapters change the interface.
- Limits: identity and
instanceofbreak; self-calls bypass the wrapper; big interfaces need forwarding.
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?
Decorators let toppings stack and repeat at run time with one class per topping. Booleans can't express double portions and the price method grows with every topping; subclasses explode combinatorially.
2. In new BufferedReader(new InputStreamReader(new FileInputStream(f))), which layer is not a decorator?
InputStreamReader changes the interface from InputStream to Reader, so it is an adapter. BufferedReader wraps a Reader and is a Reader: a decorator. FileInputStream is the concrete component and wraps nothing.
3. A web app wraps its handler as withAuth(withLogging(handler)). Security complains that rejected login attempts never appear in the logs. Why?
The outer wrapper runs first. withAuth rejects the request and returns without calling inward, so withLogging never sees it. Swap them: withLogging(withAuth(handler)).
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?
Decorators intercept calls that go through the wrapper. A call the inner object makes on itself never leaves the inner object. Spring's proxies have the same self-invocation limit.
5. What is the key difference between Decorator and Proxy, given that their class diagrams are identical?
Both keep the interface and hold one object. Intent separates them: decorators add features and are stacked by clients; proxies decide whether, when and how the real object is used.
6. An interface you decorate has 25 methods and gains new ones every release. What reduces the risk of decorators silently breaking?
A base class like FilterInputStream forwards all methods once; real decorators override only what they change, and new methods are forwarded in one place. Subclassing the concrete class loses run-time composition.
Score 60% or more and the lesson is marked complete.