Skip to content

Decorator: Add Behaviour by Wrapping, the Way Middleware Does

Learn the Decorator pattern by stacking auth, caching and timing around an API handler that keeps the same interface, with TypeScript, Python and PHP code.

13 min readDesign patternStructural

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.

Router talks to Handler; decorators implement Handler and wrap another Handler.Router calls Handler (handle(req)). Router creates LogTiming (builds stack). SlotsHandler implements Handler. HandlerDecorator implements Handler. HandlerDecorator has a Handler (wraps inner). RequireApiKey inherits from HandlerDecorator. CacheResponses inherits from HandlerDecorator. LogTiming inherits from HandlerDecorator.Routerassembles the stackper route«interface»Handlerhandle(req):ApiResponseSlotsHandlercore: looks up freeslots«abstract»HandlerDecoratorinner: Handler;delegatesRequireApiKey401 unless x-api-keyis validCacheResponsesGET 200s kept forttlMsLogTiminglogs method, path,status, msStack orderLogTiming >RequireApiKey …handle(req)builds stackwraps inner
Router talks to Handler; decorators implement Handler and wrap another Handler.

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 inner Handler, 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 Handler interface.

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)`); // 1

When 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 Handler alone.

  • 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 LogTiming times 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.

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

  2. Move the core behaviour into a concrete component that implements the interface and contains no cross-cutting logic.

  3. Create an abstract base decorator that implements the same interface, takes an inner instance in its constructor, and forwards every method to it.

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

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

  6. 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 handle frames 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 SlotsHandler stop 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.

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.

Next guide5 of 7 · Structural patternsFacade Pattern: One Simple Entry Point to a Messy SubsystemRead the next one