Decorator
Adding behaviour to objects dynamically by wrapping them — stacking decorators, Java I/O streams, Python function decorators, middleware, and decorator vs inheritance.
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:
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);class DataSource(Protocol):
def write(self, data: bytes) -> None: ...
def read(self) -> bytes: ...
class FileDataSource:
def __init__(self, path): self.path = path
def write(self, data): open(self.path, "wb").write(data)
def read(self): return open(self.path, "rb").read()
class Compressed:
def __init__(self, inner: DataSource): self.inner = inner
def write(self, data): self.inner.write(zlib.compress(data))
def read(self): return zlib.decompress(self.inner.read())
class Encrypted:
def __init__(self, inner: DataSource, key: bytes):
self.inner, self.f = inner, Fernet(key)
def write(self, data): self.inner.write(self.f.encrypt(data))
def read(self): return self.f.decrypt(self.inner.read())
ds = Encrypted(Compressed(FileDataSource("backup.bin")), key)
ds.write(payload)interface DataSource {
write(data: Uint8Array): Promise<void>;
read(): Promise<Uint8Array>;
}
class FileDataSource implements DataSource {
constructor(private path: string) {}
write(data: Uint8Array) { return fs.writeFile(this.path, data); }
async read() { return new Uint8Array(await fs.readFile(this.path)); }
}
class Compressed implements DataSource {
constructor(private inner: DataSource) {}
write(data: Uint8Array) { return this.inner.write(gzipSync(data)); }
async read() { return gunzipSync(await this.inner.read()); }
}
const ds: DataSource = new Encrypted(new Compressed(new FileDataSource("backup.bin")), key);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
| Where | Example |
|---|---|
| Java I/O | new BufferedReader(new InputStreamReader(new FileInputStream(f))) |
| Collections | Collections.unmodifiableList(list), synchronizedMap(map) |
| HTTP middleware | Express/Koa middleware, ASP.NET pipeline, Go http.Handler wrappers |
| Python | @functools.cache, @retry, @login_required — function decorators |
| Caching layers | A CachingRepository wrapping a Repository |
| React | Higher-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): ...// Higher-order functions do the same in TS
const timed = <A extends unknown[], R>(fn: (...a: A) => Promise<R>) =>
async (...args: A): Promise<R> => {
const t = performance.now();
try { return await fn(...args); }
finally { console.log(`${fn.name} took ${(performance.now() - t).toFixed(1)}ms`); }
};
const fetchUser = timed(async (id: string) => (await fetch(`/users/${id}`)).json());// Java: wrap a functional interface
static <T, R> Function<T, R> timed(Function<T, R> fn) {
return x -> {
long start = System.nanoTime();
try { return fn.apply(x); }
finally { System.out.printf("took %d µs%n", (System.nanoTime() - start) / 1000); }
};
}
Function<String, User> load = timed(repo::findById);- 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.
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.