Decorator
Wrap an object in another object with the same interface to add behaviour, such as caching, logging or retries, without changing the original.
Description
A decorator implements the same interface as the object it wraps and holds a reference to it. Each call does a little extra work before or after forwarding to the wrapped object. To the caller it looks exactly like the original.
Because every decorator has the same interface, they stack like layers: logging around caching around the real API. You compose features at runtime instead of creating a subclass for every combination, such as CachingLoggingRetryingFetcher.
Class diagram
Decorator pattern class diagram
- Interface Fetcher with + get(url): string.
- Class ApiFetcher with + get(url): string.
- Abstract class FetcherDecorator with + get(url): string.
- Class CachingFetcher with + get(url).
- Class LoggingFetcher with + get(url).
- ApiFetcher implements Fetcher.
- FetcherDecorator implements Fetcher.
- FetcherDecorator wraps Fetcher.
- CachingFetcher extends FetcherDecorator.
- LoggingFetcher extends FetcherDecorator.
Sequence diagram
Decorator pattern sequence diagram
- Client → LoggingFetcher: get("/products/mug").
- LoggingFetcher → CachingFetcher: get(url).
- CachingFetcher → ApiFetcher: get(url).
- CachingFetcher receives "JSON" back from ApiFetcher.
- LoggingFetcher receives "JSON" back from CachingFetcher.
- LoggingFetcher → LoggingFetcher: record "GET /products/mug".
- Client receives "JSON" back from LoggingFetcher.
TypeScript example
Caching and logging stacked around a fetcher. Each layer has the same interface; the second request for the same URL never reaches the real API.
// Decorator: add caching and logging around a data fetcher without changing it.
interface Fetcher {
get(url: string): string;
}
// Concrete component: the real work
class ApiFetcher implements Fetcher {
calls = 0;
get(url: string): string {
this.calls += 1;
return `{"url":"${url}","price":42}`; // pretend this is a network call
}
}
// Base decorator: same interface, forwards to the wrapped object
abstract class FetcherDecorator implements Fetcher {
protected readonly inner: Fetcher;
constructor(inner: Fetcher) {
this.inner = inner;
}
get(url: string): string {
return this.inner.get(url);
}
}
class CachingFetcher extends FetcherDecorator {
private readonly cache = new Map<string, string>();
get(url: string): string {
const hit = this.cache.get(url);
if (hit !== undefined) return hit;
const fresh = super.get(url);
this.cache.set(url, fresh);
return fresh;
}
}
class LoggingFetcher extends FetcherDecorator {
readonly log: string[] = [];
get(url: string): string {
const started = this.log.length;
const result = super.get(url);
this.log.push(`GET ${url} (#${started + 1})`);
return result;
}
}
export function demo(): string[] {
const api = new ApiFetcher();
// Stack decorators like layers: logging → caching → real API
const logging = new LoggingFetcher(new CachingFetcher(api));
const fetcher: Fetcher = logging;
fetcher.get("/products/mug");
fetcher.get("/products/mug"); // served from the cache
fetcher.get("/products/pen");
return [...logging.log, `real API calls: ${api.calls}`];
}When to use it
Use it when
- You want optional, combinable features around an object: caching, logging, metrics, retries, authorization, compression.
- Subclassing would explode into combinations, or the class is final or third-party.
- Different callers need different stacks of behaviour around the same core object.
- Cross-cutting concerns should stay out of the core business logic.
Avoid it when
- There is only ever one extra behaviour, always applied. Put it in the class or a single wrapper function.
- The added behaviour needs to change the interface. That's an Adapter.
- Order-dependent stacks are getting hard to reason about. A small explicit pipeline or middleware chain may be clearer.
Pitfalls
- Order matters: logging outside the cache logs every call, logging inside logs only cache misses. Document the intended order and build stacks in one place.
- Identity checks break: a decorated object is not
===the original, andinstanceofsees the decorator. - Large interfaces make every decorator forward many methods. Keep the decorated interface small, or use a base decorator that forwards by default.
- Deep stacks are hard to debug from a stack trace. Name decorators clearly.
Alternatives
Proxy
Choose it when you control access to or the lifecycle of the real object (lazy loading, permissions), rather than adding features.
Chain of Responsibility
Choose it when each handler may decide to stop the request instead of always forwarding it.
Higher-order functions / middleware
Choose it when the interface is one function: withCache(withLogging(fetch)) is the functional decorator.
Strategy
Choose it when you want to replace the core behaviour, not wrap extra behaviour around it.