Attach additional responsibilities to an object dynamically by wrapping it. You need flexible, runtime composition of behavior. Inheritance would
Decorator
Overview
Attach additional responsibilities to an object dynamically by wrapping it.
When to use
- You need flexible, runtime composition of behavior.
- Inheritance would lead to too many subclasses.
Java example
TypeScript example
Pros and cons
Pros:
- Behavior can be added without subclassing.
- Multiple decorators can be combined.
Cons:
- Many small objects can be hard to debug.
- Order of decorators matters.
Common pitfalls
- Hiding side effects in deep decorator stacks.
- Mutating shared state across decorators.