LLDintermediate
Decorator Pattern
Decorator adds behavior dynamically to objects without creating a large inheritance hierarchy. It is useful for concerns like logging, metrics, caching, or compression.
Reading time
9 min
decoratorpatternscompositionextensibility
Why Decorator Exists
If you try to model every optional feature combination with inheritance, the class tree becomes unmanageable. Decorators wrap behavior at runtime instead.
Typical Uses
- Logging wrappers
- Metrics collection
- Caching layers
- Compression or encryption wrappers
Benefits
- Composable behavior
- Better flexibility than subclassing
- Aligns well with composition over inheritance
Interview Tip
Use decorator when responsibilities are optional and orthogonal to the core object.