Decorator Design Pattern Explained
Decorator lets you attach new behavior to an object dynamically by wrapping it in another object with the same interface, without modifying the original clas...
Published November 12, 2026
The Decorator pattern wraps an object to add behaviour dynamically without modifying its class or using inheritance. Decorators can be stacked.
The concept
A decorator implements the same interface as the object it wraps and delegates to it, adding something before or after the call.
Examples: logging, caching, compression streams, middleware and Python's @decorator syntax.
Layers around the core
Practical examples
Function decorator
const withLog = (fn) => (...a) => { console.log('call', a); return fn(...a) }
const add = withLog((x, y) => x + y)Class-based
interface Repo { function find(int $id); }
class CachedRepo implements Repo {
function __construct(private Repo $inner, private Cache $c) {}
function find(int $id) { return $this->c->remember("u$id", fn() => $this->inner->find($id)); }
}Python syntax
@lru_cache(maxsize=128)
def fib(n): return n if n < 2 else fib(n-1) + fib(n-2)Common mistakes
- Long decorator chains that are hard to debug.
- Changing the interface in a wrapper.
- Order mistakes (cache before auth).
Key takeaways
- Wrap to add behaviour.
- Same interface as the wrapped object.
- Stack in the right order.
FAQ
Decorator vs inheritance?
Decorators add behaviour at runtime and can be combined; subclasses are fixed at compile time.
Decorator vs Proxy?
Proxy controls access; decorator adds responsibilities.