Decorator#
The Decorator pattern is a structural design pattern that allows behavior to be added to individual objects, either statically or dynamically, without affecting the behavior of other objects from the same class. This pattern creates a decorator class which wraps the original class and provides additional functionality while keeping the class methods signature intact.
Imagine you have a class with a method that you want to extend without modifying the original class. You can create a decorator class that extends the original class and adds the new functionality. That means that the original class still adheres to the Open–Closed principle. The Decorator pattern is a good alternative to subclassing when you want to add new functionality to an object without changing its structure.
UML Diagram#
+-------------------+ +-------------------+
| Component |<-------| ConcreteComponent|
|-------------------| |-------------------|
| +operation() | | +operation() |
+-------------------+ +-------------------+
^
|
+-------------------+
| Decorator |
|-------------------|
| -component: Component |
| +operation() |
+-------------------+
^
|
+-------------------+
| ConcreteDecorator |
|-------------------|
| +operation() |
+-------------------+
In this diagram, Component is an interface with a method operation(). ConcreteComponent is a class that implements the Component interface. Decorator is an abstract class that also implements the Component interface and has a reference to a Component object. ConcreteDecorator is a class that extends Decorator and adds additional behavior to the operation() method.
--- Java Example ------ Python Example ---