Attach extra responsibilities to an object dynamically by wrapping it in objects that implement the same interface and delegate to it. Decorators give you a flexible alternative to subclassing for combining features.
Decorator lets you add behaviour to an object by wrapping it in another object that has the same interface. The caller cannot tell whether it is talking to the original or to a wrapper, so you can stack as many wrappers as you like and pick the combination at runtime. If you have used HTTP middleware in Express, Django, Laravel or ASP.NET, you already know the shape: each layer receives a request, may do something before or after, and passes it on to the next layer. This guide builds that idea from scratch as a classic Decorator, so you can explain both the pattern and the frameworks you use every day.
The problem
A situation where the obvious design starts to hurt.
Fernbrook Clinics runs 14 physiotherapy clinics. A team of four engineers owns the booking API that the front-desk tablets and the public website call. The busiest endpoint is GET /clinics/{id}/slots, which returns the free appointment times for a clinic. The waiting-room kiosks poll it every 10 seconds, and each call runs a fairly expensive availability query.
The core logic lives in a SlotsHandler class with a single method, handle(request). Over a few months the team needed three cross-cutting concerns: reject requests without a valid x-api-key, cache successful GET responses for 30 seconds, and log how long each request took.
The first attempt put all three into handle as if-blocks. The method tripled in length, and the same blocks were copied into the five other handlers. The second attempt used inheritance: AuthenticatedSlotsHandler, CachedSlotsHandler, CachedAuthenticatedSlotsHandler, and so on. Three independent concerns give 8 possible combinations per handler, and with six handlers that is up to 48 classes. Worse, the public website needs caching and timing but no API key, while the admin endpoints need auth and timing but must never be cached. Every new concern doubles the number of classes, and nobody can change the order of the steps without rewriting the hierarchy.
The solution
What the pattern proposes.
Keep the Handler interface tiny: one method, handle(request): response. SlotsHandler implements it and contains only the slot-lookup logic.
Then write each concern as a separate class that also implements Handler and holds a reference to another Handler, called the inner handler. RequireApiKey checks the header and either returns 401 or delegates. CacheResponses returns a stored response if one is still fresh, otherwise delegates and stores the result. LogTiming reads the clock, delegates, and logs the elapsed time. A small abstract base, HandlerDecorator, stores the inner handler and delegates by default so each concrete decorator only overrides what it changes.
At startup, the router assembles the stack it wants for each route: new LogTiming(new RequireApiKey(new CacheResponses(new SlotsHandler()))). The website route simply leaves out RequireApiKey. Six handlers plus three decorators is nine classes instead of 48, and adding a fourth concern, such as rate limiting, is one new class.
Order is now explicit and matters. Putting RequireApiKey outside CacheResponses means a request without a key is rejected before it can read cached data. Putting LogTiming outermost means the logged time includes auth and cache lookups. This is exactly how middleware pipelines work: each middleware is a decorator around everything inside it.
An everyday analogy
The same idea, outside software.
Think of posting a fragile ceramic vase. The vase itself does not change. You wrap it in bubble wrap, put it in a box, and the post office adds a tracking label. Each layer adds one thing, protection, structure, traceability, and each one still presents itself to the next handler as 'a parcel to be moved'. You can skip the bubble wrap for a book or add an insurance sticker for jewellery without inventing a new kind of parcel. And the order matters: the label goes on the outside of the box, not on the vase.
Structure
The pieces and how they relate.
Participants
- Handler (component interface)
- The single operation every layer shares:
handle(req)returns a response. Clients depend only on this, which is what lets wrappers and the core be swapped freely. - SlotsHandler (concrete component)
- The object being decorated. It knows how to find free appointment slots and nothing about auth, caching or logging.
- HandlerDecorator (base decorator)
- Implements
Handler, holds a reference to an innerHandler, and forwards calls to it by default. Concrete decorators extend it and override only what they change. - RequireApiKey, CacheResponses, LogTiming (concrete decorators)
- Each adds one behaviour before and/or after delegating: short-circuiting with 401, returning a stored response, or measuring elapsed time.
- Router (client and composition root)
- Decides which decorators wrap which handler and in what order, then calls the outermost one through the
Handlerinterface.
Pseudocode
The solution to the scenario, language-neutral.
interface Handler
method handle(req): Response
class SlotsHandler implements Handler
method handle(req)
slots = availability query for the clinic
return Response(200, slots as JSON)
abstract class HandlerDecorator implements Handler
field inner: Handler
constructor(inner)
this.inner = inner
method handle(req)
return inner.handle(req)
class RequireApiKey extends HandlerDecorator
field validKeys
method handle(req)
if req.headers["x-api-key"] not in validKeys
return Response(401, "missing or invalid API key")
return inner.handle(req)
class CacheResponses extends HandlerDecorator
field ttlMs, entries = empty map
method handle(req)
if req.method != "GET"
return inner.handle(req)
entry = entries[req.path]
if entry exists and entry.expiresAt > now()
return entry.response
response = inner.handle(req)
if response.status == 200
entries[req.path] = (now() + ttlMs, response)
return response
class LogTiming extends HandlerDecorator
method handle(req)
start = now()
response = inner.handle(req)
log(req.method, req.path, response.status, now() - start)
return response
// Router, at startup
core = new SlotsHandler()
kioskRoute = new LogTiming(new RequireApiKey(new CacheResponses(core, 30000), keys))
websiteRoute = new LogTiming(new CacheResponses(core, 30000))The code
The same solution in TypeScript, Python and PHP.
interface ApiRequest {
method: string;
path: string;
headers: Record<string, string>;
}
interface ApiResponse {
status: number;
body: string;
}
interface Handler {
handle(req: ApiRequest): ApiResponse;
}
class SlotsHandler implements Handler {
calls = 0;
handle(req: ApiRequest): ApiResponse {
this.calls++;
const slots = ["09:00", "09:30", "11:15"];
return { status: 200, body: JSON.stringify({ clinic: "north", slots }) };
}
}
abstract class HandlerDecorator implements Handler {
constructor(protected readonly inner: Handler) {}
handle(req: ApiRequest): ApiResponse {
return this.inner.handle(req);
}
}
class RequireApiKey extends HandlerDecorator {
constructor(inner: Handler, private readonly validKeys: Set<string>) {
super(inner);
}
handle(req: ApiRequest): ApiResponse {
const key = req.headers["x-api-key"];
if (key === undefined || !this.validKeys.has(key)) {
return { status: 401, body: "missing or invalid API key" };
}
return super.handle(req);
}
}
class CacheResponses extends HandlerDecorator {
private readonly entries = new Map<string, { expiresAt: number; response: ApiResponse }>();
constructor(
inner: Handler,
private readonly ttlMs: number,
private readonly now: () => number = () => performance.now(),
) {
super(inner);
}
handle(req: ApiRequest): ApiResponse {
if (req.method !== "GET") {
return super.handle(req);
}
const t = this.now();
const hit = this.entries.get(req.path);
if (hit !== undefined && hit.expiresAt > t) {
return hit.response;
}
const response = super.handle(req);
if (response.status === 200) {
this.entries.set(req.path, { expiresAt: t + this.ttlMs, response });
}
return response;
}
}
class LogTiming extends HandlerDecorator {
constructor(
inner: Handler,
private readonly log: (line: string) => void,
private readonly now: () => number = () => performance.now(),
) {
super(inner);
}
handle(req: ApiRequest): ApiResponse {
const start = this.now();
const response = super.handle(req);
const ms = this.now() - start;
this.log(`${req.method} ${req.path} -> ${response.status} in ${ms.toFixed(1)}ms`);
return response;
}
}
// Router: assemble the kiosk stack once at startup.
const core = new SlotsHandler();
const kioskApi: Handler = new LogTiming(
new RequireApiKey(new CacheResponses(core, 30_000), new Set(["front-desk-7"])),
(line) => console.log(line),
);
const withKey: ApiRequest = {
method: "GET",
path: "/clinics/north/slots",
headers: { "x-api-key": "front-desk-7" },
};
kioskApi.handle(withKey); // miss: core runs
kioskApi.handle(withKey); // hit: served from cache
kioskApi.handle({ ...withKey, headers: {} }); // 401 before the cache is read
console.log(`core handler ran ${core.calls} time(s)`); // 1import json
import time
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from typing import Callable, Optional
@dataclass(frozen=True)
class ApiRequest:
method: str
path: str
headers: dict[str, str] = field(default_factory=dict)
@dataclass(frozen=True)
class ApiResponse:
status: int
body: str
class Handler(ABC):
@abstractmethod
def handle(self, req: ApiRequest) -> ApiResponse: ...
class SlotsHandler(Handler):
def __init__(self) -> None:
self.calls = 0
def handle(self, req: ApiRequest) -> ApiResponse:
self.calls += 1
slots = ["09:00", "09:30", "11:15"]
return ApiResponse(200, json.dumps({"clinic": "north", "slots": slots}))
class HandlerDecorator(Handler):
def __init__(self, inner: Handler) -> None:
self._inner = inner
def handle(self, req: ApiRequest) -> ApiResponse:
return self._inner.handle(req)
class RequireApiKey(HandlerDecorator):
def __init__(self, inner: Handler, valid_keys: set[str]) -> None:
super().__init__(inner)
self._valid_keys = valid_keys
def handle(self, req: ApiRequest) -> ApiResponse:
key = req.headers.get("x-api-key")
if key is None or key not in self._valid_keys:
return ApiResponse(401, "missing or invalid API key")
return super().handle(req)
class CacheResponses(HandlerDecorator):
def __init__(
self,
inner: Handler,
ttl_ms: float,
now: Optional[Callable[[], float]] = None,
) -> None:
super().__init__(inner)
self._ttl_ms = ttl_ms
self._now = now or (lambda: time.monotonic() * 1000)
self._entries: dict[str, tuple[float, ApiResponse]] = {}
def handle(self, req: ApiRequest) -> ApiResponse:
if req.method != "GET":
return super().handle(req)
t = self._now()
hit = self._entries.get(req.path)
if hit is not None and hit[0] > t:
return hit[1]
response = super().handle(req)
if response.status == 200:
self._entries[req.path] = (t + self._ttl_ms, response)
return response
class LogTiming(HandlerDecorator):
def __init__(
self,
inner: Handler,
log: Callable[[str], None],
now: Optional[Callable[[], float]] = None,
) -> None:
super().__init__(inner)
self._log = log
self._now = now or (lambda: time.perf_counter() * 1000)
def handle(self, req: ApiRequest) -> ApiResponse:
start = self._now()
response = super().handle(req)
ms = self._now() - start
self._log(f"{req.method} {req.path} -> {response.status} in {ms:.1f}ms")
return response
if __name__ == "__main__":
# Router: assemble the kiosk stack once at startup.
core = SlotsHandler()
kiosk_api: Handler = LogTiming(
RequireApiKey(CacheResponses(core, 30_000), {"front-desk-7"}),
print,
)
with_key = ApiRequest("GET", "/clinics/north/slots", {"x-api-key": "front-desk-7"})
kiosk_api.handle(with_key) # miss: core runs
kiosk_api.handle(with_key) # hit: served from cache
kiosk_api.handle(ApiRequest("GET", "/clinics/north/slots")) # 401 before the cache is read
print(f"core handler ran {core.calls} time(s)") # 1<?php
declare(strict_types=1);
final class ApiRequest
{
/** @param array<string, string> $headers */
public function __construct(
public readonly string $method,
public readonly string $path,
public readonly array $headers = [],
) {}
}
final class ApiResponse
{
public function __construct(
public readonly int $status,
public readonly string $body,
) {}
}
interface Handler
{
public function handle(ApiRequest $req): ApiResponse;
}
final class SlotsHandler implements Handler
{
public int $calls = 0;
public function handle(ApiRequest $req): ApiResponse
{
$this->calls++;
$slots = ['09:00', '09:30', '11:15'];
return new ApiResponse(200, json_encode(['clinic' => 'north', 'slots' => $slots], JSON_THROW_ON_ERROR));
}
}
abstract class HandlerDecorator implements Handler
{
public function __construct(protected readonly Handler $inner) {}
public function handle(ApiRequest $req): ApiResponse
{
return $this->inner->handle($req);
}
}
final class RequireApiKey extends HandlerDecorator
{
/** @param list<string> $validKeys */
public function __construct(Handler $inner, private readonly array $validKeys)
{
parent::__construct($inner);
}
public function handle(ApiRequest $req): ApiResponse
{
$key = $req->headers['x-api-key'] ?? null;
if ($key === null || !in_array($key, $this->validKeys, true)) {
return new ApiResponse(401, 'missing or invalid API key');
}
return parent::handle($req);
}
}
final class CacheResponses extends HandlerDecorator
{
/** @var array<string, array{0: float, 1: ApiResponse}> */
private array $entries = [];
private \Closure $now;
public function __construct(Handler $inner, private readonly float $ttlMs, ?\Closure $now = null)
{
parent::__construct($inner);
$this->now = $now ?? static fn (): float => hrtime(true) / 1e6;
}
public function handle(ApiRequest $req): ApiResponse
{
if ($req->method !== 'GET') {
return parent::handle($req);
}
$t = ($this->now)();
$hit = $this->entries[$req->path] ?? null;
if ($hit !== null && $hit[0] > $t) {
return $hit[1];
}
$response = parent::handle($req);
if ($response->status === 200) {
$this->entries[$req->path] = [$t + $this->ttlMs, $response];
}
return $response;
}
}
final class LogTiming extends HandlerDecorator
{
private \Closure $now;
public function __construct(Handler $inner, private readonly \Closure $log, ?\Closure $now = null)
{
parent::__construct($inner);
$this->now = $now ?? static fn (): float => hrtime(true) / 1e6;
}
public function handle(ApiRequest $req): ApiResponse
{
$start = ($this->now)();
$response = parent::handle($req);
$ms = ($this->now)() - $start;
($this->log)(sprintf('%s %s -> %d in %.1fms', $req->method, $req->path, $response->status, $ms));
return $response;
}
}
// Router: assemble the kiosk stack once at startup.
$core = new SlotsHandler();
$kioskApi = new LogTiming(
new RequireApiKey(new CacheResponses($core, 30000), ['front-desk-7']),
static function (string $line): void {
echo $line, PHP_EOL;
},
);
$withKey = new ApiRequest('GET', '/clinics/north/slots', ['x-api-key' => 'front-desk-7']);
$kioskApi->handle($withKey); // miss: core runs
$kioskApi->handle($withKey); // hit: served from cache
$kioskApi->handle(new ApiRequest('GET', '/clinics/north/slots')); // 401 before the cache is read
echo "core handler ran {$core->calls} time(s)", PHP_EOL; // 1When to use it
Situations where it pays off.
You need to add behaviour to individual objects without changing their class or the code that uses them.
Wrapping happens at construction time, so the slot lookup code stays untouched and callers keep depending on
Handleralone.Several optional features can be combined in many ways, and subclassing would need a class for every combination.
Each feature becomes one class. Combinations are assembled at runtime, so n features cost n classes instead of up to 2 to the power of n.
Cross-cutting concerns such as auth, caching, retries, metrics or logging surround many different operations.
A decorator written against the interface works for every implementation of it, so
LogTimingtimes the slots handler and the admin handler alike.You cannot or should not subclass the original, for example a final class or a third-party client.
Decorator relies on composition, not inheritance, so it only needs the interface the object already implements.
The order of steps must be configurable per use, as in an HTTP middleware pipeline.
Nesting order is the execution order, and each route can choose its own stack without new classes.
How to implement it
Steps to introduce it in existing code.
Identify the interface the client already uses and make sure it is small. If it has many methods, every decorator must forward all of them, so consider narrowing it first.
Move the core behaviour into a concrete component that implements the interface and contains no cross-cutting logic.
Create an abstract base decorator that implements the same interface, takes an inner instance in its constructor, and forwards every method to it.
Write one concrete decorator per concern. Override the method, add your logic before or after calling the inner object, or return early to short-circuit.
Build the stack in one place, such as the router or a factory, and decide the order deliberately: security checks usually sit outside caches, and timing usually sits outermost.
Test each decorator in isolation by wrapping a small fake handler, then add one integration test that checks the assembled stack.
Pros and cons
What you gain and what you pay.
Pros
- Add or remove behaviour at runtime by changing how objects are wrapped, without touching the core class.
- Avoids the combinatorial explosion of subclasses when features are optional and independent.
- Each decorator has a single responsibility and can be tested with a fake inner object.
- Works with any implementation of the interface, including classes you do not own.
- Makes execution order explicit and easy to change per use case.
Cons
- A deep stack of small wrappers can be hard to debug; stack traces show several
handleframes before the real work. - Order dependence is easy to get wrong, for example caching before auth can leak data to unauthenticated callers.
- Object identity changes: the outer object is not the core instance, so type checks or equality against
SlotsHandlerstop working. - Wide interfaces make every decorator forward many methods it does not care about.
- Configuring the stack can produce long nested constructor calls unless you add a builder or a compose helper.
Relations with other guides
Patterns it's often confused or combined with.
- Proxy Pattern: Control Access with a Stand-In Object
Proxy has the same structure, a wrapper with the same interface, but its purpose is controlling access to one subject, and it usually manages that subject's lifecycle itself. Decorators are stacked by the client to add features.
- Adapter Pattern: Fit a Third-Party SDK Into Your Own Interface
Adapter wraps an object to give it a different interface. Decorator keeps the interface identical and changes behaviour instead.
- Chain of Responsibility: Pass a Request Along Until One Handles It
Both pass a request through linked objects. In Chain of Responsibility any link may handle the request and stop; in Decorator every layer normally delegates and the core always does the main work.
- Composite Pattern: Treat Single Items and Groups Through One Interface
A decorator is like a composite with exactly one child. Both rely on recursive composition through a shared interface, and they combine well.
- Strategy: swap the rule without touching who uses it
Strategy changes the inside of an object by swapping an algorithm it holds. Decorator changes the outside by wrapping the whole object.
- Retry with Backoff: Exponential Delays, Jitter and Retry Budgets
Retry, timeout and circuit-breaker logic around a remote client is usually implemented as decorators over the client interface, the same way
CacheResponseswraps the handler here.
Common questions
Short answers to the usual doubts.
How is Express or Laravel middleware related to the Decorator pattern?
A middleware stack is a chain of decorators around the final route handler. Each middleware sees the request, can act before calling next, can act after it returns, or can respond early. Frameworks usually express it with functions and a next callback instead of classes, but the structure is the same: every layer has the same contract as the thing it wraps. Because a layer may stop the request, middleware also borrows from Chain of Responsibility, which is worth mentioning in an interview.
What is the difference between Decorator and Proxy?
Structurally they are nearly identical. The difference is intent and who controls the wrapping. A proxy stands in for one subject to control access to it, such as lazy creation, remote access or permission checks, and often creates the subject itself. Decorators are composed by the client, are meant to be stacked, and exist to add features. In practice an auth wrapper like RequireApiKey could be described either way, so explain the intent you have in mind.
Why not just use inheritance?
Inheritance fixes the combination at compile time and gives one class per combination. With three independent concerns that is up to 8 variants per handler, and the order of steps is baked into the hierarchy. Decorators are combined at runtime, each concern is written once, and the same decorator works for every implementation of the interface.
Are Python's @decorators the same thing as the Decorator pattern?
They share the idea of wrapping, but not the mechanics. A Python @decorator replaces a function or class at definition time with a wrapped version, so every call site gets the wrapped behaviour. The GoF pattern wraps object instances at runtime, so two instances of the same class can have different stacks. You can use function decorators to implement the pattern for callables, but they are not equivalent.
Does the order of decorators matter?
Yes. The outermost decorator runs first on the way in and last on the way out. In the Fernbrook stack, putting CacheResponses outside RequireApiKey would let a request without a key receive cached slot data, because the cache would answer before the key check ran. Put security checks outside caches and put timing outermost if you want the total cost.
What should I watch out for when decorating an interface with many methods?
Every decorator must forward every method, even the ones it does not change, or it silently breaks callers. A base decorator class that forwards everything helps, but a wide interface still means more surface to get wrong. If you only need to decorate one operation, consider extracting a narrower interface for it first.