Decorator

Adding behaviour to objects dynamically by wrapping them — stacking decorators, Java I/O streams, Python function decorators, middleware, and decorator vs inheritance.

Intermediate 2 min readLesson 9 of 24 Interview Q&A

Intent: attach additional responsibilities to an object dynamically, by wrapping it in another object with the same interface. Decorators are a flexible alternative to subclassing for extending behaviour.

Because each decorator implements the same interface and holds a reference to the next object, you can stack them in any order:

ClientMetricsdecoratorRetrydecoratorCachedecoratorHttpClientreal object

Each layer does its work before and/or after delegating to the next — like layers of an onion.

Example: composable data sources

interface DataSource {
    void write(byte[] data);
    byte[] read();
}

class FileDataSource implements DataSource {
    private final Path path;
    FileDataSource(Path path) { this.path = path; }
    public void write(byte[] data) { Files.write(path, data); }
    public byte[] read() { return Files.readAllBytes(path); }
}

// Base decorator: delegates everything
abstract class DataSourceDecorator implements DataSource {
    protected final DataSource inner;
    DataSourceDecorator(DataSource inner) { this.inner = inner; }
    public void write(byte[] data) { inner.write(data); }
    public byte[] read() { return inner.read(); }
}

class CompressionDecorator extends DataSourceDecorator {
    CompressionDecorator(DataSource inner) { super(inner); }
    @Override public void write(byte[] data) { inner.write(gzip(data)); }
    @Override public byte[] read() { return gunzip(inner.read()); }
}

class EncryptionDecorator extends DataSourceDecorator {
    private final SecretKey key;
    EncryptionDecorator(DataSource inner, SecretKey key) { super(inner); this.key = key; }
    @Override public void write(byte[] data) { inner.write(encrypt(data, key)); }
    @Override public byte[] read() { return decrypt(inner.read(), key); }
}

// Compose at runtime: compress, then encrypt, then write to file
DataSource ds = new EncryptionDecorator(
                    new CompressionDecorator(
                        new FileDataSource(Path.of("backup.bin"))), key);
ds.write(payload);

Why not subclass?

With inheritance you'd need CompressedFile, EncryptedFile, CompressedEncryptedFile, EncryptedCompressedS3… one class per combination. Decorators give you N small classes that combine in any order, chosen at runtime.

Decorators in the wild

WhereExample
Java I/Onew BufferedReader(new InputStreamReader(new FileInputStream(f)))
CollectionsCollections.unmodifiableList(list), synchronizedMap(map)
HTTP middlewareExpress/Koa middleware, ASP.NET pipeline, Go http.Handler wrappers
Python@functools.cache, @retry, @login_required — function decorators
Caching layersA CachingRepository wrapping a Repository
ReactHigher-order components (withRouter(Component))

Python function decorators

Python's @decorator syntax applies the same idea to functions: a function that takes a function and returns a wrapped one.

import functools, time

def timed(fn):
    @functools.wraps(fn)                  # keep name/docstring
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        try:
            return fn(*args, **kwargs)
        finally:
            print(f"{fn.__name__} took {time.perf_counter() - start:.3f}s")
    return wrapper

def retry(times=3):
    def deco(fn):
        @functools.wraps(fn)
        def wrapper(*args, **kwargs):
            for attempt in range(times):
                try:
                    return fn(*args, **kwargs)
                except ConnectionError:
                    if attempt == times - 1:
                        raise
        return wrapper
    return deco

@timed
@retry(times=3)                           # applied bottom-up: timed(retry(fetch))
def fetch(url): ...
Key takeaways
  • Decorator wraps an object with the same interface to add behaviour before/after delegating.
  • Decorators stack in any order at runtime — no subclass explosion.
  • Seen in Java I/O, middleware, caching layers and Python's @ syntax.
  • Decorator keeps the interface; Adapter changes it; Proxy controls access.
Interview questions
QHow does the decorator pattern differ from inheritance?medium

Inheritance adds behaviour statically, per class, and combining features requires a subclass per combination. Decorators add behaviour dynamically per object by wrapping it in objects sharing the same interface; small decorators combine in any order at runtime. Java's I/O streams are the canonical example.