Decorator Pattern
- •
What it is
- •
a structural pattern that adds responsibilities to an object dynamically, at runtime, without modifying its original class
- •
- •
Analogy
- •
wrapping a gift in layers — the gift stays the same, but ribbons, stickers, and labels can be added flexibly on top
- •
- •
Problem it solves
- •
avoids "class explosion" from needing a subclass for every possible feature combination (e.g.
CoffeeWithMilkAndSoyAndWhip)
- •
- •
How it works
- •
define a core component (interface/abstract class); implement a concrete component (e.g.
Espresso); create an abstract decorator that also implements the component interface; create concrete decorators (e.g.Mocha,Whip) that wrap a component and add behavior
- •
- •
Benefits
- •
flexible/reusable, avoids excessive subclassing, allows changing behavior at runtime, supports the Open-Closed Principle
- •
- •
Related