decorator pattern
What problem does the decorator pattern solve?
- Add new features without changing the original functionality and code
- Optional, dynamically adjustable functions for different situations
Decorators, as the name suggests, are used to decorate other physical objects, adding to the function of the object being decorated without changing the object being decorated. This is like when we buy a car, the same model, there are many features are optional, but the core function of the car remains unchanged. We can buy, according to the need to optional different configurations.
How is this achieved?
Imagine you are a decorator and if you want to decorate a car, then you first need to have a car and you cannot change the original functionality (interface) of the car during the decoration process.
As shown in the class diagram:
- The core functionality Core and all decorators must implement the Interface interface
- All decorators save interface instances in a combinatorial manner
class Core: def some_action(): pass class Decorator: def __init__(self,core): = core def some_action(): .... .some_action() .....
python decorator syntactic sugar
Decorators are so common that python's specialized syntactic sugar simplifies their use. The outermost function takes a function object and returns the inner function, which is the true executing function.
# Decorator definitions def decorator(func): def wrapper(*args,**kwargs): ..... result = func(*args,**kwargs) .... return result return wrapper # Decorator usage @decorator def func(): pass
Although the form has changed, the substance has not:Save interface instances that implement the same interface.
- Saving the interface instance is easy to understand because the function func object is passed in.
- How does implementing the same interface make sense? The syntactic sugar @xxxx operates equivalently to the
func = decorator(func)
, i.e., the inner function renames the original function name.
to this article on the python design patterns of the decorator pattern is introduced to this article, more related python decorator content please search for my previous articles or continue to browse the following related articles I hope you will support me in the future more!