Design Pattern
Decorator Design Pattern
“linked list of features”
The decorator design pattern allows us to add new behaviors to objects dynamically by placing them inside special wrapper objects, called decorators.
When to use Decorator Pattern
Add / remove behavior at run-time with a polymorphic class.
Resources
Formally learned in CS247.
Pieces of the decorator pattern:
- Abstract Component: Gives the interface for our classes
- Concrete Component: Implements the “basic” version of the interface
- Abstract Decorator: Organizes decorators and has-a decorator or the concrete component.
- Concrete Decorators: Implement the interface, call
operation()
on the next object in this linked list.
Template code for a Pizza example (UML below)
StuffedCrust → Topping → Topping → CrustAndSauce
Motivation
Consider the following design scenario, where we want to enable customization for a windowing (GUI) system.
If we attempt to make a class for each possible feature, for n features, there are 2n possible configurations. Combinatorial explosion!
The solution is to use a decorator design pattern!
ScrollBar → Tabbing → Basic Window