On this page

Decorator

A decorator wraps an object, implements the same interface as the object it wraps, and adds something on the way through: compression, encryption, buffering, metrics, retries. Because the wrapper looks exactly like the thing it wraps, you can wrap the wrapper, and build up behaviour one layer at a time at runtime instead of baking every combination into a class hierarchy.

The structural patterns overview shows Decorator with a short TypeScript example. This page goes deeper: why subclassing breaks down, a full stackable implementation in three languages, how Java's IO library is built from decorators, how Python's @decorator syntax relates to the pattern (it's related, but it isn't the same thing), how web middleware is decorators in disguise, and the one thing that bites everyone eventually: the order of the layers changes the result.

Intent

Attach extra responsibilities to an object dynamically, by wrapping it in an object with the same interface, so that behaviours can be combined freely without a subclass for every combination.

The key ideas:

  • Same interface. A decorated object can be passed anywhere the plain one could. The client doesn't change.
  • Wraps one object. Each decorator holds exactly one inner object of the same type and delegates to it.
  • Adds behaviour. It does something before, after or around the delegated call: transforms the input, transforms the output, records something, or repeats the call.
  • Composes at runtime. Which layers are present, and in what order, is decided when objects are wired together, not when classes are written.

That last point is the whole reason the pattern exists. It's an application of composition over inheritance, and it keeps classes open for extension and closed for modification: a new behaviour is a new decorator, and nothing existing is edited.

The problem

You're building a small storage layer for an internal document service. It stores blobs by key. Product asks for compression, because documents are repetitive text. Security asks for encryption at rest. Ops asks for a byte counter. Some deployments need all three, some need one, a test setup needs none.

The first attempt uses flags:

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.zip.*;

class BlobStore {
    private final Map<String, byte[]> blobs = new HashMap<>();
    private final boolean compress, encrypt, meter;
    private final byte key;
    long bytesWritten;

    BlobStore(boolean compress, boolean encrypt, boolean meter, byte key) {
        this.compress = compress; this.encrypt = encrypt; this.meter = meter; this.key = key;
    }

    void put(String k, byte[] data) {
        if (meter) bytesWritten += data.length;
        if (compress) data = deflate(data);
        if (encrypt) data = xor(data);           // must stay AFTER compress, see below
        blobs.put(k, data);
    }

    byte[] get(String k) {
        byte[] data = blobs.get(k);
        if (encrypt) data = xor(data);           // and the reverse order here
        if (compress) data = inflate(data);
        return data;
    }

    private byte[] xor(byte[] in) {               // toy "encryption", illustration only
        byte[] out = new byte[in.length];
        for (int i = 0; i < in.length; i++) out[i] = (byte) (in[i] ^ key);
        return out;
    }

    private static byte[] deflate(byte[] in) {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        try (DeflaterOutputStream out = new DeflaterOutputStream(bytes)) { out.write(in); }
        catch (IOException e) { throw new UncheckedIOException(e); }
        return bytes.toByteArray();
    }

    private static byte[] inflate(byte[] in) {
        try (InflaterInputStream s = new InflaterInputStream(new ByteArrayInputStream(in))) { return s.readAllBytes(); }
        catch (IOException e) { throw new UncheckedIOException(e); }
    }
}

class Demo {
    public static void main(String[] args) {
        byte[] doc = "status=OK;".repeat(100).getBytes(StandardCharsets.UTF_8);
        BlobStore store = new BlobStore(true, true, true, (byte) 0x5A);
        store.put("a", doc);
        assert Arrays.equals(store.get("a"), doc);
        assert store.bytesWritten == doc.length;
        System.out.println("before: works, with three flags and two hand-ordered if-chains");
    }
}
import zlib


class BlobStore:
    def __init__(self, compress: bool, encrypt: bool, meter: bool, key: int) -> None:
        self._blobs: dict[str, bytes] = {}
        self._compress, self._encrypt, self._meter, self._key = compress, encrypt, meter, key
        self.bytes_written = 0

    def put(self, k: str, data: bytes) -> None:
        if self._meter:
            self.bytes_written += len(data)
        if self._compress:
            data = zlib.compress(data)
        if self._encrypt:                       # must stay AFTER compress
            data = bytes(b ^ self._key for b in data)
        self._blobs[k] = data

    def get(self, k: str) -> bytes:
        data = self._blobs[k]
        if self._encrypt:                       # and the reverse order here
            data = bytes(b ^ self._key for b in data)
        if self._compress:
            data = zlib.decompress(data)
        return data


doc = b"status=OK;" * 100
store = BlobStore(compress=True, encrypt=True, meter=True, key=0x5A)
store.put("a", doc)
assert store.get("a") == doc
assert store.bytes_written == len(doc)
print("before: works, with three flags and two hand-ordered if-chains")

It works for three features. Look at where it goes:

  1. Every feature edits the same class. Adding checksums, caching or a size limit means another flag, another constructor parameter and two more if statements in exactly the right places. Each change risks breaking the others.
  2. The order is hard-coded in two places that must mirror each other. put applies compress then encrypt, and get must undo them in the reverse order. Nothing enforces that the two sequences agree.
  3. Unused features are still there. A test that wants a plain map still carries compression code, key handling and a counter.
  4. The alternative is worse. Replacing flags with subclasses gives CompressedBlobStore, EncryptedBlobStore, CompressedEncryptedBlobStore, MeteredCompressedBlobStore and so on. With n optional features that's up to 2n classes, and that's before you allow different orders.
  5. Behaviour can't change per instance at runtime. You can't take an existing store and add metering to it for one request path.

What we want is to write each feature once, in its own small class, and stack them.

Structure

classDiagram
    direction TB
    class BlobStore {
        <<interface>>
        +put(key, data)
        +get(key) bytes
    }
    class InMemoryBlobStore {
        +put(key, data)
        +get(key) bytes
    }
    class BlobStoreDecorator {
        <<abstract>>
        #inner BlobStore
        +put(key, data)
        +get(key) bytes
    }
    class CompressingBlobStore {
        +put(key, data)
        +get(key) bytes
    }
    class EncryptingBlobStore {
        -key bytes
        +put(key, data)
        +get(key) bytes
    }
    class MeteredBlobStore {
        +bytesWritten long
        +put(key, data)
    }
    BlobStore <|.. InMemoryBlobStore
    BlobStore <|.. BlobStoreDecorator
    BlobStoreDecorator o--> BlobStore : wraps one
    BlobStoreDecorator <|-- CompressingBlobStore
    BlobStoreDecorator <|-- EncryptingBlobStore
    BlobStoreDecorator <|-- MeteredBlobStore

The unusual-looking part is that BlobStoreDecorator both is a BlobStore and has a BlobStore. That double relationship is what lets decorators nest. A call travels inward through each layer on the way to the real store, and the result travels back out:

sequenceDiagram
    participant C as Client
    participant M as MeteredBlobStore
    participant Z as CompressingBlobStore
    participant E as EncryptingBlobStore
    participant S as InMemoryBlobStore
    C->>M: put("a", 1000 bytes)
    M->>M: count 1000 bytes
    M->>Z: put("a", 1000 bytes)
    Z->>Z: deflate to about 30 bytes
    Z->>E: put("a", 30 bytes)
    E->>E: encrypt
    E->>S: put("a", 30 bytes)
    C->>M: get("a")
    M->>Z: get("a")
    Z->>E: get("a")
    E->>S: get("a")
    S-->>E: 30 encrypted bytes
    E-->>Z: 30 compressed bytes
    Z-->>M: 1000 bytes
    M-->>C: 1000 bytes

Notice that get undoes the layers in reverse order automatically. The before-code needed two mirrored if chains. With decorators, the call stack does it for you.

Participants

ParticipantIn the exampleResponsibility
ComponentBlobStoreThe interface shared by the real object and every decorator.
Concrete componentInMemoryBlobStoreThe object that does the core job. Knows nothing about decorators.
Decorator (base)BlobStoreDecoratorHolds a reference to a component and forwards every method to it by default. Optional, but saves boilerplate when the interface has many methods.
Concrete decoratorsCompressingBlobStore, EncryptingBlobStore, MeteredBlobStoreEach overrides only the methods it cares about and adds one behaviour around the delegated call.
Client / wiring codemainChooses which decorators to apply and in what order.

The base decorator class deserves a word. If the interface has two methods, skipping it and forwarding by hand is fine. If it has fifteen (think java.util.List), a forwarding base lets each concrete decorator override only what it changes. Guava's ForwardingList and the Jakarta Servlet HttpServletRequestWrapper are exactly this: a class that forwards everything, made to be subclassed.

Implementation

The implementation has a real store, a forwarding base, and three decorators. The demo stacks them, proves the data round-trips, and then stacks them in the wrong order to show what changes.

The "encryption" here is a toy

To keep the samples dependency-free and identical across languages, EncryptingBlobStore XORs data with a SHA-256-based keystream. It has no nonce and no authentication, and it reuses the keystream for every blob. Don't use it for real data. Use an authenticated cipher such as AES-GCM (javax.crypto in Java, the cryptography package in Python, crypto.createCipheriv("aes-256-gcm", ...) in Node). The decorator structure stays exactly the same.

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.zip.*;

interface BlobStore {
    void put(String key, byte[] data);
    byte[] get(String key);
}

// Concrete component: the core job, nothing else.
final class InMemoryBlobStore implements BlobStore {
    private final Map<String, byte[]> blobs = new HashMap<>();

    public void put(String key, byte[] data) { blobs.put(key, data.clone()); }

    public byte[] get(String key) {
        byte[] b = blobs.get(key);
        if (b == null) throw new NoSuchElementException(key);
        return b.clone();
    }

    int storedSize(String key) { return blobs.get(key).length; }
}

// Base decorator: forwards everything, so subclasses override only what they change.
abstract class BlobStoreDecorator implements BlobStore {
    protected final BlobStore inner;
    BlobStoreDecorator(BlobStore inner) { this.inner = Objects.requireNonNull(inner); }
    public void put(String key, byte[] data) { inner.put(key, data); }
    public byte[] get(String key) { return inner.get(key); }
}

final class CompressingBlobStore extends BlobStoreDecorator {
    CompressingBlobStore(BlobStore inner) { super(inner); }

    @Override public void put(String key, byte[] data) { inner.put(key, deflate(data)); }
    @Override public byte[] get(String key) { return inflate(inner.get(key)); }

    private static byte[] deflate(byte[] in) {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        try (DeflaterOutputStream out = new DeflaterOutputStream(bytes)) { out.write(in); }
        catch (IOException e) { throw new UncheckedIOException(e); }
        return bytes.toByteArray();
    }

    private static byte[] inflate(byte[] in) {
        try (InflaterInputStream s = new InflaterInputStream(new ByteArrayInputStream(in))) {
            return s.readAllBytes();
        } catch (IOException e) { throw new UncheckedIOException(e); }
    }
}

// Toy cipher, illustration only (see the warning above).
final class EncryptingBlobStore extends BlobStoreDecorator {
    private final byte[] key;

    EncryptingBlobStore(BlobStore inner, byte[] key) { super(inner); this.key = key.clone(); }

    @Override public void put(String k, byte[] data) { inner.put(k, xorKeystream(data)); }
    @Override public byte[] get(String k) { return xorKeystream(inner.get(k)); }

    private byte[] xorKeystream(byte[] data) {
        try {
            MessageDigest sha = MessageDigest.getInstance("SHA-256");
            byte[] out = new byte[data.length];
            for (int block = 0; block * 32 < data.length; block++) {
                sha.update(key);
                byte[] ks = sha.digest(ByteBuffer.allocate(4).putInt(block).array());
                for (int i = 0; i < 32 && block * 32 + i < data.length; i++) {
                    out[block * 32 + i] = (byte) (data[block * 32 + i] ^ ks[i]);
                }
            }
            return out;
        } catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e); }
    }
}

// Only overrides put; get is inherited from the forwarding base.
final class MeteredBlobStore extends BlobStoreDecorator {
    long bytesWritten;
    MeteredBlobStore(BlobStore inner) { super(inner); }
    @Override public void put(String key, byte[] data) {
        bytesWritten += data.length;
        inner.put(key, data);
    }
}

class Demo {
    public static void main(String[] args) {
        byte[] doc = "status=OK;".repeat(500).getBytes(StandardCharsets.UTF_8);   // 5,000 repetitive bytes
        byte[] key = "demo-key".getBytes(StandardCharsets.UTF_8);

        // Right order: compress, THEN encrypt. Two meters show logical vs physical bytes.
        InMemoryBlobStore disk = new InMemoryBlobStore();
        MeteredBlobStore physical = new MeteredBlobStore(disk);
        MeteredBlobStore logical = new MeteredBlobStore(
                new CompressingBlobStore(new EncryptingBlobStore(physical, key)));

        logical.put("a", doc);
        assert Arrays.equals(logical.get("a"), doc);
        assert logical.bytesWritten == 5_000;
        assert physical.bytesWritten < 200 : "compressed before encryption";
        assert !new String(disk.get("a"), StandardCharsets.ISO_8859_1).contains("status");

        // Wrong order: encrypt, THEN compress. Still correct, but encrypted bytes don't compress.
        InMemoryBlobStore disk2 = new InMemoryBlobStore();
        BlobStore wrongOrder = new EncryptingBlobStore(new CompressingBlobStore(disk2), key);
        wrongOrder.put("a", doc);
        assert Arrays.equals(wrongOrder.get("a"), doc);
        assert disk2.storedSize("a") > 4_900;

        // No decorators at all, for tests.
        BlobStore plain = new InMemoryBlobStore();
        plain.put("a", doc);
        assert Arrays.equals(plain.get("a"), doc);

        System.out.printf("stored bytes: right order %d, wrong order %d%n",
                disk.storedSize("a"), disk2.storedSize("a"));
    }
}
import hashlib
import zlib
from typing import Protocol


class BlobStore(Protocol):
    def put(self, key: str, data: bytes) -> None: ...
    def get(self, key: str) -> bytes: ...


class InMemoryBlobStore:
    """Concrete component: the core job, nothing else."""

    def __init__(self) -> None:
        self._blobs: dict[str, bytes] = {}

    def put(self, key: str, data: bytes) -> None:
        self._blobs[key] = bytes(data)

    def get(self, key: str) -> bytes:
        return self._blobs[key]

    def stored_size(self, key: str) -> int:
        return len(self._blobs[key])


class BlobStoreDecorator:
    """Base decorator: forwards everything, so subclasses override only what they change."""

    def __init__(self, inner: BlobStore) -> None:
        self._inner = inner

    def put(self, key: str, data: bytes) -> None:
        self._inner.put(key, data)

    def get(self, key: str) -> bytes:
        return self._inner.get(key)


class CompressingBlobStore(BlobStoreDecorator):
    def put(self, key: str, data: bytes) -> None:
        self._inner.put(key, zlib.compress(data))

    def get(self, key: str) -> bytes:
        return zlib.decompress(self._inner.get(key))


class EncryptingBlobStore(BlobStoreDecorator):
    """Toy cipher, illustration only (see the warning above)."""

    def __init__(self, inner: BlobStore, key: bytes) -> None:
        super().__init__(inner)
        self._key = key

    def _xor_keystream(self, data: bytes) -> bytes:
        out = bytearray(len(data))
        for block in range(0, len(data), 32):
            ks = hashlib.sha256(self._key + (block // 32).to_bytes(4, "big")).digest()
            for i, b in enumerate(data[block:block + 32]):
                out[block + i] = b ^ ks[i]
        return bytes(out)

    def put(self, key: str, data: bytes) -> None:
        self._inner.put(key, self._xor_keystream(data))

    def get(self, key: str) -> bytes:
        return self._xor_keystream(self._inner.get(key))


class MeteredBlobStore(BlobStoreDecorator):
    """Only overrides put; get is inherited from the forwarding base."""

    def __init__(self, inner: BlobStore) -> None:
        super().__init__(inner)
        self.bytes_written = 0

    def put(self, key: str, data: bytes) -> None:
        self.bytes_written += len(data)
        self._inner.put(key, data)


if __name__ == "__main__":
    doc = b"status=OK;" * 500           # 5,000 repetitive bytes
    key = b"demo-key"

    disk = InMemoryBlobStore()
    physical = MeteredBlobStore(disk)
    logical = MeteredBlobStore(CompressingBlobStore(EncryptingBlobStore(physical, key)))

    logical.put("a", doc)
    assert logical.get("a") == doc
    assert logical.bytes_written == 5_000
    assert physical.bytes_written < 200, "compressed before encryption"
    assert b"status" not in disk.get("a")

    disk2 = InMemoryBlobStore()
    wrong_order = EncryptingBlobStore(CompressingBlobStore(disk2), key)
    wrong_order.put("a", doc)
    assert wrong_order.get("a") == doc
    assert disk2.stored_size("a") > 4_900

    plain = InMemoryBlobStore()
    plain.put("a", doc)
    assert plain.get("a") == doc
    print(f"stored bytes: right order {disk.stored_size('a')}, wrong order {disk2.stored_size('a')}")
import assert from "node:assert/strict";
import { createHash } from "node:crypto";
import { deflateSync, inflateSync } from "node:zlib";

interface BlobStore {
  put(key: string, data: Uint8Array): void;
  get(key: string): Uint8Array;
}

// Concrete component: the core job, nothing else.
class InMemoryBlobStore implements BlobStore {
  private readonly blobs = new Map<string, Uint8Array>();
  put(key: string, data: Uint8Array): void {
    this.blobs.set(key, Uint8Array.from(data));
  }
  get(key: string): Uint8Array {
    const b = this.blobs.get(key);
    if (!b) throw new Error(`no blob ${key}`);
    return Uint8Array.from(b);
  }
  storedSize(key: string): number {
    return this.blobs.get(key)?.length ?? 0;
  }
}

// Base decorator: forwards everything, so subclasses override only what they change.
abstract class BlobStoreDecorator implements BlobStore {
  constructor(protected readonly inner: BlobStore) {}
  put(key: string, data: Uint8Array): void {
    this.inner.put(key, data);
  }
  get(key: string): Uint8Array {
    return this.inner.get(key);
  }
}

class CompressingBlobStore extends BlobStoreDecorator {
  override put(key: string, data: Uint8Array): void {
    this.inner.put(key, deflateSync(data));
  }
  override get(key: string): Uint8Array {
    return inflateSync(this.inner.get(key));
  }
}

// Toy cipher, illustration only (see the warning above).
class EncryptingBlobStore extends BlobStoreDecorator {
  constructor(inner: BlobStore, private readonly key: Uint8Array) {
    super(inner);
  }
  private xorKeystream(data: Uint8Array): Uint8Array {
    const out = new Uint8Array(data.length);
    for (let block = 0; block * 32 < data.length; block++) {
      const counter = Buffer.alloc(4);
      counter.writeUInt32BE(block);
      const ks = createHash("sha256").update(this.key).update(counter).digest();
      for (let i = 0; i < 32 && block * 32 + i < data.length; i++) {
        out[block * 32 + i] = data[block * 32 + i]! ^ ks[i]!;
      }
    }
    return out;
  }
  override put(key: string, data: Uint8Array): void {
    this.inner.put(key, this.xorKeystream(data));
  }
  override get(key: string): Uint8Array {
    return this.xorKeystream(this.inner.get(key));
  }
}

// Only overrides put; get is inherited from the forwarding base.
class MeteredBlobStore extends BlobStoreDecorator {
  bytesWritten = 0;
  override put(key: string, data: Uint8Array): void {
    this.bytesWritten += data.length;
    this.inner.put(key, data);
  }
}

const doc = new TextEncoder().encode("status=OK;".repeat(500)); // 5,000 repetitive bytes
const key = new TextEncoder().encode("demo-key");

const disk = new InMemoryBlobStore();
const physical = new MeteredBlobStore(disk);
const logical = new MeteredBlobStore(
  new CompressingBlobStore(new EncryptingBlobStore(physical, key)),
);

logical.put("a", doc);
assert.deepEqual(Buffer.from(logical.get("a")), Buffer.from(doc));
assert.equal(logical.bytesWritten, 5_000);
assert.ok(physical.bytesWritten < 200, "compressed before encryption");
assert.ok(!Buffer.from(disk.get("a")).toString("latin1").includes("status"));

const disk2 = new InMemoryBlobStore();
const wrongOrder = new EncryptingBlobStore(new CompressingBlobStore(disk2), key);
wrongOrder.put("a", doc);
assert.deepEqual(Buffer.from(wrongOrder.get("a")), Buffer.from(doc));
assert.ok(disk2.storedSize("a") > 4_900);

console.log(
  `stored bytes: right order ${disk.storedSize("a")}, wrong order ${disk2.storedSize("a")}`,
);

What the demo shows

One feature, one class. Each decorator is a few lines and has a single reason to change. Compression can be tested by wrapping an in-memory store and checking that get(put(x)) == x. Nothing about keys or counters gets in the way.

The client chooses the combination. Production can use Metered(Compressing(Encrypting(disk))). A test can use InMemoryBlobStore alone. A debugging session can add a logging decorator to a single instance. None of those combinations needed a new class.

Position changes meaning, not just correctness. There are two MeteredBlobStores in the right-order stack, and they report different numbers. The outer one counts the logical bytes the application wrote (5,000). The inner one, sitting under encryption and compression, counts the physical bytes that reach storage (a few dozen). Both are useful. They're different metrics, and the only difference is where the decorator sits.

The wrong order still round-trips, and that's what makes it dangerous. Encrypting(Compressing(disk)) stores and retrieves data correctly, so a round-trip test passes. But good encryption output looks random, and random data doesn't compress, so the stored blob is bigger than the original instead of about 1% of it. No test that only checks correctness will catch this. You need a test that asserts the property you actually care about (here, stored size).

Ordering: the part that bites

Because every decorator has the same interface, the type system can't tell you that one order is right and another is wrong. These are the ordering rules worth knowing:

LayersRight order (outermost first)What goes wrong otherwise
Compression and encryptionCompress, then encrypt (compress is outer on write)Encrypted data doesn't compress. Separately, compressing secrets alongside attacker-controlled data can leak information through output size (the CRIME and BREACH attacks on TLS and HTTP compression).
Authorisation and cachingAuthorisation outside the cacheA shared cache answers a second user without the check running.
Retry and timeoutDepends on intent: retry outside timeout gives each attempt its own deadline, timeout outside retry gives the whole operation one budgetRetrying inside a per-request deadline means later attempts may never get a chance.
Retry and circuit breakerUsually retry outside, breaker inside, so each attempt is counted and an open breaker fails fastRetrying around an open breaker just burns attempts against a known failure.
Metrics and cachingMetrics outside the cache to measure what callers see, inside to measure load on the backendDashboards that silently measure the wrong thing.
Error handling and everything elseError translation outermostErrors thrown by outer layers escape untranslated.
Buffering and compression in streamsBuffer outside the compressor when writing many small valuesMany tiny writes into a compressor are slow.

Two practical habits help. First, build the stack in exactly one place (a factory method or the composition root) and give it a name, such as productionBlobStore(disk, key), so the order is written down once. Second, write a test for the order-dependent property, not just for round-tripping, like the stored-size assertion above. The circuit breaker page goes deeper on combining resilience layers.

Java IO: a library built from decorators

The best-known decorator stack in any standard library is java.io. InputStream and OutputStream are the component interfaces (abstract classes, technically). FileInputStream and ByteArrayInputStream are concrete components. FilterInputStream and FilterOutputStream are the forwarding base decorators, and BufferedInputStream, DataInputStream, GZIPInputStream, CheckedInputStream and friends are concrete decorators. You build the behaviour you want by nesting constructors.

Python's io module is layered the same way: a raw binary stream at the bottom, a BufferedReader or BufferedWriter over it, and a TextIOWrapper on top that adds text decoding. gzip.GzipFile can wrap any binary file object.

import java.io.*;
import java.util.*;
import java.util.zip.*;

class Demo {
    public static void main(String[] args) throws IOException {
        List<String> words = List.of("alpha", "beta", "gamma");

        // Write: typed values -> buffer -> gzip -> bytes in memory.
        ByteArrayOutputStream sink = new ByteArrayOutputStream();
        try (DataOutputStream out = new DataOutputStream(
                new BufferedOutputStream(new GZIPOutputStream(sink)))) {
            out.writeInt(words.size());
            for (String w : words) out.writeUTF(w);
        } // closing the OUTERMOST stream flushes and closes every layer beneath it

        byte[] gz = sink.toByteArray();
        assert (gz[0] & 0xFF) == 0x1F && (gz[1] & 0xFF) == 0x8B : "gzip magic number";

        // Read: the mirror-image stack.
        List<String> read = new ArrayList<>();
        try (DataInputStream in = new DataInputStream(
                new BufferedInputStream(new GZIPInputStream(new ByteArrayInputStream(gz))))) {
            int n = in.readInt();
            for (int i = 0; i < n; i++) read.add(in.readUTF());
        }
        assert read.equals(words);

        // The classic bug: never closing (or flushing) the outer stream.
        ByteArrayOutputStream sink2 = new ByteArrayOutputStream();
        DataOutputStream leaky = new DataOutputStream(
                new BufferedOutputStream(new GZIPOutputStream(sink2)));
        leaky.writeUTF("where did this go?");
        assert sink2.size() == 10 : "only the gzip header; the data is stuck in the buffer";
        leaky.close();
        assert sink2.size() > 10;

        System.out.println("java.io decorator stack ok, " + gz.length + " gzip bytes");
    }
}
import gzip
import io

lines = ["alpha", "beta", "gamma"]

# Write: text -> TextIOWrapper (encoding + buffer) -> GzipFile -> BytesIO.
raw = io.BytesIO()
with io.TextIOWrapper(gzip.GzipFile(fileobj=raw, mode="wb"), encoding="utf-8", newline="\n") as out:
    for line in lines:
        out.write(line + "\n")
# Closing the outer layer closes the GzipFile, which does NOT close the BytesIO it was given.
data = raw.getvalue()
assert data[:2] == b"\x1f\x8b"                       # gzip magic number

# Read: the mirror-image stack.
with io.TextIOWrapper(gzip.GzipFile(fileobj=io.BytesIO(data), mode="rb"), encoding="utf-8") as f:
    assert f.read().splitlines() == lines

# The classic bug: the text layer buffers, so nothing reaches gzip until it's flushed.
raw2 = io.BytesIO()
leaky = io.TextIOWrapper(gzip.GzipFile(fileobj=raw2, mode="wb"), encoding="utf-8", newline="\n")
leaky.write("where did this go?\n")
before = len(raw2.getvalue())
leaky.close()
after = len(raw2.getvalue())
assert before < after
assert gzip.decompress(raw2.getvalue()) == b"where did this go?\n"
print(f"io decorator stack ok, {len(data)} gzip bytes")

Lessons from Java IO that apply to any decorator design:

  • Close the outermost layer, and only that one. Each decorator's close() flushes its own state and then closes the layer it wraps. Closing an inner layer directly skips the outer layers' flush, and the last chunk of data is lost. In the demo, ten bytes (the gzip header written by the constructor) reached memory. The actual data sat in BufferedOutputStream's buffer until close().
  • Some decorators change the interface. DataInputStream adds readInt and readUTF on top of InputStream. Strictly, the GoF pattern keeps the interface the same. Java IO bends that rule, which is why you hold the stack by its outermost, most specific type.
  • Reading and writing stacks mirror each other. If you write through Data(Buffered(GZIP(sink))), you read through Data(Buffered(GZIP(source))). Getting one layer out of order is a corrupt-data bug.
  • Constructor nesting gets noisy. That's the readability cost of the pattern. Java 7's Files.newBufferedReader and Python's gzip.open(path, "rt") are small facades that build the common stacks for you.

Python's @decorator syntax is not (quite) the pattern

Python's @ syntax is called "decorator", and it's easy to assume it's the GoF pattern. They share an idea, wrapping something to add behaviour while keeping its interface, but they differ in what's wrapped and when:

GoF Decorator patternPython @decorator
WrapsAn objectA function or class (any callable)
WhenAt runtime, when objects are wiredAt definition time, when the def or class statement runs
ScopePer instance: one store can be compressed, another notEvery caller of that function gets the wrapped version
MechanismA class implementing the same interfaceA higher-order function returning a new callable
Removing itBuild the object without that layerEdit the source, or reach for __wrapped__

@functools.lru_cache, @functools.wraps, @property, @staticmethod and @dataclass are all uses of the syntax. Some of them do decorate in the pattern's sense (lru_cache wraps a function in a caching layer with the same call signature). Others, such as @dataclass, generate code and return the same class modified, which isn't wrapping at all.

The two can work together. A function decorator can be applied to one object's method at runtime, which gets you per-instance behaviour:

import functools
from collections.abc import Callable


def retry[**P, R](times: int, on: tuple[type[Exception], ...]) -> Callable[[Callable[P, R]], Callable[P, R]]:
    """A decorator factory: @retry(3, (ConnectionError,)) retries the wrapped callable."""
    def wrap(fn: Callable[P, R]) -> Callable[P, R]:
        @functools.wraps(fn)               # keep __name__, __doc__, and set __wrapped__
        def inner(*args: P.args, **kwargs: P.kwargs) -> R:
            for attempt in range(1, times + 1):
                try:
                    return fn(*args, **kwargs)
                except on:
                    if attempt == times:
                        raise
            raise AssertionError("unreachable")
        return inner
    return wrap


calls = {"n": 0}


@retry(3, (ConnectionError,))              # definition time: EVERY caller gets the retries
def fetch_rate(currency: str) -> float:
    """Pretend to call a slow, flaky exchange-rate API."""
    calls["n"] += 1
    if calls["n"] < 3:
        raise ConnectionError("flaky")
    return 1.08 if currency == "EUR" else 1.0


assert fetch_rate("EUR") == 1.08 and calls["n"] == 3
assert fetch_rate.__name__ == "fetch_rate"           # thanks to functools.wraps
assert fetch_rate.__wrapped__ is not fetch_rate      # the original is still reachable


class RatesClient:
    def __init__(self) -> None:
        self.attempts = 0

    def rate(self, currency: str) -> float:
        self.attempts += 1
        if self.attempts < 2:
            raise ConnectionError("flaky")
        return 1.08


# Runtime, per instance: only this client retries. That's the GoF pattern's behaviour.
patient = RatesClient()
patient.rate = retry(2, (ConnectionError,))(patient.rate)    # type: ignore[method-assign]
impatient = RatesClient()

assert patient.rate("EUR") == 1.08
try:
    impatient.rate("EUR")
    raise AssertionError("the undecorated instance should fail")
except ConnectionError:
    pass
print("function decorators ok")

A practical rule: use @decorator syntax for behaviour that should apply to a function everywhere (caching a pure function, registering a route, timing an endpoint). Use the object pattern when the behaviour should vary per instance or per environment (encryption on in production, off in tests). And always use functools.wraps, or tracebacks, logs and introspection tools will report every function as inner.

TypeScript has its own decorator syntax (TC39 decorators, supported natively since TypeScript 5.0, alongside the older experimentalDecorators used by Angular and NestJS). Like Python's, it's applied at class definition time and works on classes, methods, accessors and fields. Same caveat: it shares the name, and only some uses match the pattern.

Middleware chains are decorators

Web frameworks are full of decorators that don't use the word. A request handler is a function from request to response. A middleware takes a handler and returns a new handler with the same signature that does something before and after calling the original. That's the Decorator pattern applied to functions, and the stack of middleware is the stack of wrappers.

Koa (and the many frameworks modelled on it) makes this explicit: each middleware does await next() and the code after that line runs on the way back out, giving the "onion" model. Express middleware (req, res, next) is closer to a chain of responsibility: each piece can end the response or pass control on, and there's no clean "after" step without hooks such as res.on("finish"). Redux middleware wraps dispatch, and Python's ASGI and WSGI middleware wrap the application callable.

The example below composes middleware Koa-style and demonstrates the ordering rule for error handling.

import assert from "node:assert/strict";

interface Req { path: string; user?: string }
interface Res { status: number; body: string }
type Handler = (req: Req) => Promise<Res>;
type Middleware = (next: Handler) => Handler;

class HttpError extends Error {
  constructor(readonly status: number, message: string) {
    super(message);
  }
}

// compose(a, b, c)(h) === a(b(c(h))): the first middleware is the outermost layer.
const compose =
  (...layers: Middleware[]) =>
  (handler: Handler): Handler =>
    layers.reduceRight((next, layer) => layer(next), handler);

const trace =
  (name: string, log: string[]): Middleware =>
  (next) =>
  async (req) => {
    log.push(`${name}>`);
    try {
      return await next(req);
    } finally {
      log.push(`${name}<`);
    }
  };

const requireUser: Middleware = (next) => async (req) => {
  if (!req.user) throw new HttpError(401, "login required");
  return next(req);
};

const errorsToResponses: Middleware = (next) => async (req) => {
  try {
    return await next(req);
  } catch (e) {
    if (e instanceof HttpError) return { status: e.status, body: e.message };
    return { status: 500, body: "internal error" };
  }
};

const hello: Handler = async (req) => ({ status: 200, body: `hello ${req.user}` });

async function main(): Promise<void> {
  // Onion order: outer layers run first on the way in and last on the way out.
  const log: string[] = [];
  const app = compose(errorsToResponses, trace("outer", log), trace("inner", log), requireUser)(hello);
  assert.deepEqual(await app({ path: "/", user: "asha" }), { status: 200, body: "hello asha" });
  assert.deepEqual(log, ["outer>", "inner>", "inner<", "outer<"]);

  // Error handling outermost: the auth failure becomes a 401 response.
  assert.deepEqual(await app({ path: "/" }), { status: 401, body: "login required" });

  // Error handling placed INSIDE auth: the 401 escapes as an exception.
  const misordered = compose(requireUser, errorsToResponses)(hello);
  await assert.rejects(misordered({ path: "/" }), HttpError);
  console.log("middleware onion ok");
}

main().catch((e) => {
  console.error(e);
  process.exit(1);
});
from collections.abc import Callable
from dataclasses import dataclass


@dataclass(frozen=True)
class Req:
    path: str
    user: str | None = None


@dataclass(frozen=True)
class Res:
    status: int
    body: str


Handler = Callable[[Req], Res]
Middleware = Callable[[Handler], Handler]


class HttpError(Exception):
    def __init__(self, status: int, message: str) -> None:
        super().__init__(message)
        self.status = status


def compose(*layers: Middleware) -> Callable[[Handler], Handler]:
    """compose(a, b, c)(h) == a(b(c(h))): the first middleware is the outermost layer."""
    def build(handler: Handler) -> Handler:
        for layer in reversed(layers):
            handler = layer(handler)
        return handler
    return build


def trace(name: str, log: list[str]) -> Middleware:
    def middleware(next_: Handler) -> Handler:
        def handle(req: Req) -> Res:
            log.append(f"{name}>")
            try:
                return next_(req)
            finally:
                log.append(f"{name}<")
        return handle
    return middleware


def require_user(next_: Handler) -> Handler:
    def handle(req: Req) -> Res:
        if req.user is None:
            raise HttpError(401, "login required")
        return next_(req)
    return handle


def errors_to_responses(next_: Handler) -> Handler:
    def handle(req: Req) -> Res:
        try:
            return next_(req)
        except HttpError as e:
            return Res(e.status, str(e))
        except Exception:
            return Res(500, "internal error")
    return handle


def hello(req: Req) -> Res:
    return Res(200, f"hello {req.user}")


log: list[str] = []
app = compose(errors_to_responses, trace("outer", log), trace("inner", log), require_user)(hello)
assert app(Req("/", "asha")) == Res(200, "hello asha")
assert log == ["outer>", "inner>", "inner<", "outer<"]
assert app(Req("/")) == Res(401, "login required")

misordered = compose(require_user, errors_to_responses)(hello)
try:
    misordered(Req("/"))
    raise AssertionError("expected the 401 to escape")
except HttpError as e:
    assert e.status == 401
print("middleware onion ok")

The trace log makes the onion visible: outer> inner> on the way in, inner< outer< on the way out, the same "reverse on the way back" behaviour as the blob store's get. The misordered app is the error-handling version of the encryption-then-compression mistake: every piece is correct, and the composition is wrong. This is why frameworks document "register the error handler first" (or last, depending on their convention) so prominently.

Real-world uses

JDK

  • java.io streams, as covered above: BufferedInputStream, DataInputStream, GZIPInputStream, CheckedInputStream, PushbackInputStream, and the Reader/Writer equivalents such as BufferedReader. FilterInputStream and FilterOutputStream are the forwarding bases.
  • Collections.synchronizedList, unmodifiableList and checkedList (and the map and set versions) wrap a collection with the same interface and add locking, mutation refusal or runtime type checks. unmodifiableList is arguably a protection proxy by intent, a good example of how thin the line is.

Jakarta Servlet and Spring

  • HttpServletRequestWrapper and HttpServletResponseWrapper are forwarding base decorators in the Servlet API. Spring's ContentCachingRequestWrapper, which keeps a copy of the request body so it can be logged after it's been read, extends HttpServletRequestWrapper.
  • Servlet filters and Spring Security's filter chain wrap request processing in layers. Each filter can act before and after calling the rest of the chain.

Python

  • The io module's layering: BufferedReader over a raw stream, TextIOWrapper over a buffered stream, gzip.GzipFile over any binary file object.
  • functools.lru_cache and functools.cache wrap a function in a memoising layer with the same signature, which is the pattern applied to a callable through decorator syntax.
  • WSGI and ASGI middleware wrap the application callable. Django middleware and Starlette middleware follow this shape.

JavaScript and Node.js

  • Koa and Express middleware, with the onion-versus-chain distinction described above.
  • Redux middleware (applyMiddleware) wraps the store's dispatch function in layers such as thunk handling and logging.
  • React higher-order components take a component and return a component that renders it with extra behaviour or props. React.memo returns a wrapper that skips re-rendering when props haven't changed. Hooks replaced most hand-written HOCs, but the shape is still common in libraries.

When NOT to use it

When there's one fixed combination. If every deployment always compresses and then encrypts, a single class with two private steps is simpler to read than three classes and a wiring function. Decorators pay off when combinations vary.

When the behaviour needs the object's internals. A decorator only sees the public interface. If "add caching" requires knowing which fields changed inside the object, a decorator can't do it cleanly. Put the behaviour in the class, or redesign the interface.

When the interface is wide. Wrapping an interface with 30 methods means 30 forwarding methods (or a base class that has them), and every method added to the interface later must be added to every decorator or the forwarding base. Forgetting one means a call silently skips the decoration. Consider narrowing the interface first (interface segregation).

When identity or type matters. A decorated object isn't the original: wrapped == original is false, and wrapped instanceof EncryptingBlobStore depends on which layer is outermost. Code that uses objects as map keys, checks concrete types or calls equals across wrapped and unwrapped versions breaks in confusing ways. If you must support equality, decide explicitly whether a decorator delegates equals and hashCode to the inner object, and document it.

When you need to remove or reorder layers later. A stack of decorators is a linked list with no handle on the middle. Taking compression out of Metered(Compressing(Encrypting(disk))) means rebuilding the stack. If layers need to be toggled at runtime, a list of steps (a pipeline or chain of responsibility) that you can inspect and edit may fit better.

When the order matters and nobody will remember it. If only one order is correct, letting clients compose freely invites the mistakes shown above. Hide the composition behind a factory that builds the correct stack, and expose that instead of the individual decorators.

When debugging cost matters more than flexibility. Deep stacks produce deep stack traces, with many frames of nearly identical classes. Ten layers of middleware make a profiler's flame graph harder to read. That's a real cost to weigh, not a reason to avoid the pattern entirely.

PatternSame interface as wrapped object?PurposeTypical composer
DecoratorYesAdd behaviour, stackableThe client, explicitly
ProxyYesControl access (lazy, protected, remote, cached)Wiring code or a framework, hidden from the client
AdapterNo, converts to another interfaceMake an incompatible object fitWiring code
CompositeYesTreat a tree of objects like one objectBuilder of the tree
Chain of ResponsibilityHandlers share a handler interfacePass a request along until someone handles itConfiguration
StrategyNot a wrapperSwap the algorithm inside an objectThe client, by injection

Decorator vs Proxy. Same class diagram, different intent. A decorator adds something to the behaviour. A proxy controls access to unchanged behaviour (delaying, refusing, caching, forwarding over a network). Decorators are usually stacked deliberately by the client, while proxies are usually inserted by wiring code so the client doesn't know. Some wrappers are honestly both, and in an interview it's enough to say which intent you mean. The Proxy page has a longer comparison.

Decorator vs Composite. Both rely on recursive composition through a shared interface. A decorator has exactly one child and adds behaviour. A composite has many children and aggregates them (the size of a folder is the sum of its children). A decorator is like a composite with a single child that does extra work.

Decorator vs Chain of Responsibility. In a chain, each handler decides whether to handle the request and stop, or pass it on. In a decorator stack, every layer normally runs and delegates. Express middleware sits between the two, which is why both names get used for it.

Decorator vs Strategy. A decorator changes the "skin" of an object: it wraps from outside. A strategy changes the "guts": the object delegates part of its algorithm to a pluggable component inside. If you find yourself wrapping an object only to replace one of its steps entirely, a strategy is probably cleaner.

Decorator vs subclassing. A subclass adds behaviour at compile time, to every instance, and combinations multiply the class count. A decorator adds behaviour at runtime, to chosen instances, and combinations cost nothing. Subclassing is still right when the new behaviour needs protected internals or must apply to every instance by definition.

The smell that suggests it

  • Boolean flags that switch optional steps on and off inside a method: if (compress) ... if (encrypt) ... if (log) .... Each flag is a decorator waiting to be extracted.
  • A growing family of subclasses named after combinations: LoggingCachingRepository, CachingRepository, LoggingRepository. The names are a multiplication table.
  • Copy-pasted before-and-after code around calls to the same interface: start a timer, call, record the timer. The same three lines in front of every call to a client.
  • Needing behaviour on one instance but not another of the same class: one HTTP client with retries for idempotent reads, another without for payments.
  • A class you can't modify (third-party or shared) that needs extra behaviour. Wrapping it is often the only option that doesn't involve forking it.

The counter-smell: if every decorator in your stack reaches into the inner object's concrete type to do its job, or if there's only ever one stack and nobody varies it, the pattern is costing you more than it gives.

Interview questions

  1. "Why use a decorator instead of a subclass?" Subclassing fixes behaviour at compile time for every instance and needs a class per combination, so n optional features can need up to 2n classes. Decorators add behaviour at runtime to chosen instances, each feature is written once, and combinations come free. Subclassing is still the right call when the extension needs protected internals or applies to every instance.

  2. "Walk me through how new BufferedReader(new InputStreamReader(new FileInputStream(f))) works." FileInputStream reads raw bytes from the file. InputStreamReader converts bytes to characters using a charset. That conversion changes the interface from bytes to chars, so it's really an adapter. BufferedReader is a decorator over Reader that reads in large chunks and adds readLine(). Closing the BufferedReader closes everything beneath it.

  3. "Does the order of decorators matter? Give an example." Yes. Compress-then-encrypt shrinks data, while encrypt-then-compress doesn't, because ciphertext looks random. Authorisation must sit outside a shared cache or the cache answers unauthorised users. An error-handling middleware must be outermost to catch errors from other middleware. The fix is to build the stack in one named place and test the order-dependent property, not only round-trips.

  4. "How do Python decorators relate to the Decorator pattern?" They share the idea of wrapping to add behaviour while keeping the interface. But Python's @ decorates functions or classes at definition time, so every caller gets the wrapped version. The GoF pattern wraps individual objects at runtime. You can get per-instance behaviour in Python by applying a function decorator to one object's bound method, or by writing a wrapper class.

  5. "What problems do decorators cause with equals, hashCode and instanceof?" A decorator is a different object, so reference equality fails, and instanceof checks see only the outermost class. If decorators delegate equals to the inner object, a.equals(b) can be true while b.equals(a) is false, which breaks the symmetry rule that collections depend on. Decide a policy (usually: decorators don't override equals, and you don't mix wrapped and unwrapped objects in the same set) and avoid type checks on components.

  6. "Your interface has 20 methods and you want a logging decorator. How?" Write a forwarding base class once (like Guava's ForwardingList or HttpServletRequestWrapper) and override only the methods to log, or generate the wrapper with a dynamic proxy that intercepts every call. Mention the risk: when a method is added to the interface, the forwarding base must be updated, or decorators will miss it.

  7. "Is Express middleware the Decorator pattern?" Partly. Koa-style middleware that awaits next() and then runs more code is decorators over a handler function, giving the onion model. Express's (req, res, next) is closer to chain of responsibility, because a middleware usually either ends the response or passes it on, and there's no natural "after" phase.

  8. "Design a text-formatting feature: a document can be bold, italic, underlined, in any combination." A Text interface with render(), a PlainText component, and Bold, Italic and Underline decorators that wrap the inner render output in markup. Point out that nesting order affects the markup produced (<b><i>x</i></b> vs <i><b>x</b></i>) even when it renders the same, and that if styles need to be removed or queried later, a set of style flags on one object might be the simpler model.

  9. "How would you unit-test a decorator?" Wrap a fake or in-memory component, call through the decorator, and assert two things: that the decorator's own behaviour happened (bytes counted, data compressed) and that it delegated correctly (the inner fake saw the transformed input). Add a test for any ordering property, such as stored size after compress-then-encrypt.

  10. "When would you avoid the pattern?" When there's only one fixed combination, when behaviour needs private state of the wrapped object, when the interface is very wide, when code relies on identity or concrete types, or when layers need to be inspected and reordered at runtime, where an explicit pipeline is easier.