Structural Patterns
Decorator Pattern¶
Definition
The Decorator Pattern attaches additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.
Design Principle
- Open-Closed Principle: Classes should be open for extension, but closed for modification.
Note
- Decorators have the same supertype as the objects they decorate.
- We can pass around a decorated object in place of the original (wrapped) object.
- The decorator adds its own behaviour before and/or after delegating to the object it decorates to do the rest of the job.
- Objects can be decorated at any time, even dynamically at runtime.
Example codes
- Go example: Based on Golangbyexample.