Decorator Pattern
Problem
We want to add functionality to a static object, which is not possible using Inheritance because it is static and would apply that to the entire class.
Solution
Attach additional functionality to the object dynamically by wrapping it recursively on the client-side.
Related Patterns
- Adapter
- Proxy
- Composite
- Chain of Responsibility
Discussion
Ensure that we have a single core component and several optional embellishments. The Decorator class attaches additional responsibilities as needed.
Examples
The ornaments we put on a Christmas tree are examples of embellishments added by the Decorator. Regardless of how many things we add, it will still be recognizable as a Christmas tree. The added functionality would be the ability to light the tree up.
Code
Python has built-in support for decorators.
def debug_pop_stack(func): def debug_print_caller(func): print('() was called') return debug_print_caller @debug def foo(a, b, c): print(a, b, c) #output: foo was called