We are going to explain the Decorator design pattern and then provide a simple example in Python.
The Decorator pattern is a structural pattern that allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class.
It involves a set of decorator classes that are used to wrap concrete components. These decorators can add responsibilities to the component while maintaining the same interface.
Steps:
- Define a component interface (or abstract class) that defines the core functionality.
- Create concrete components that implement the component interface.
- Create a base decorator class that implements the component interface and has a reference to a component object.
- Create concrete decorator classes that extend the base decorator and add additional behavior.
In Python, we can use abstract base classes (ABC) to define the interface, but for simplicity we can also use duck typing.
Example: We'll create a simple coffee ordering system where we can add milk, sugar, etc. to a coffee.
Let's define:
- Coffee: the component interface (with a cost method and a description method)
- SimpleCoffee: a concrete coffee (black coffee)
- MilkDecorator, SugarDecorator: concrete decorators that add milk and sugar respectively.
We want to be able to compose decorators, so we can have a coffee with milk and sugar, for example.
Note: In Python, we can also use functions as decorators (like in the context of @decorator syntax) but that's a different use of the word "decorator".
Here we are talking about the object-oriented design pattern.
Let's code accordingly.
The Decorator design pattern is a structural pattern that allows you to dynamically add new behaviors or responsibilities to an object without modifying its existing code. It works by wrapping the original object in decorator classes that extend its functionality while maintaining the same interface.
Key Concepts:
- Component: The base object/interface being decorated.
- Concrete Component: The actual object to which decorators will be added.
- Decorator: Abstract base class that implements the component interface and holds a reference to a component.
- Concrete Decorators: Add specific functionalities to the component by overriding methods.
Simple Python Example: Coffee Shop
Imagine a coffee shop where you can add toppings (milk, sugar, etc.) to a base coffee. Each topping changes the cost and description.
# 1. Component Interface
class Coffee:
def cost(self) -> float:
pass
def description(self) -> str:
pass
# 2. Concrete Component
class SimpleCoffee(Coffee):
def cost(self) -> float:
return 2.0
def description(self) -> str:
return "Simple Coffee"
# 3. Base Decorator
class CoffeeDecorator(Coffee):
def __init__(self, coffee: Coffee):
self._coffee = coffee
def cost(self) -> float:
return self._coffee.cost()
def description(self) -> str:
return self._coffee.description()
# 4. Concrete Decorators
class MilkDecorator(CoffeeDecorator):
def cost(self) -> float:
return self._coffee.cost() + 0.5
def description(self) -> str:
return self._coffee.description() + ", Milk"
class SugarDecorator(CoffeeDecorator):
def cost(self) -> float:
return self._coffee.cost() + 0.2
def description(self) -> str:
return self._coffee.description() + ", Sugar"
# Demo
if __name__ == "__main__":
# Start with simple coffee
coffee = SimpleCoffee()
print(f"{coffee.description()}: ${coffee.cost():.2f}")
# Output: Simple Coffee: $2.00
# Add milk dynamically
coffee_with_milk = MilkDecorator(coffee)
print(f"{coffee_with_milk.description()}: ${coffee_with_milk.cost():.2f}")
# Output: Simple Coffee, Milk: $2.50
# Add sugar to the milk coffee (stacking decorators)
coffee_with_milk_and_sugar = SugarDecorator(coffee_with_milk)
print(f"{coffee_with_milk_and_sugar.description()}: ${coffee_with_milk_and_sugar.cost():.2f}")
# Output: Simple Coffee, Milk, Sugar: $2.70
How It Works:
SimpleCoffee is the base component ($2.00, "Simple Coffee").
MilkDecorator wraps any Coffee object, adding $0.50 and updating the description.
SugarDecorator similarly adds $0.20.
- Decorators can be stacked (e.g.,
SugarDecorator(MilkDecorator(SimpleCoffee()))), each adding its own behavior.
Advantages:
- Open/Closed Principle: Extend functionality without modifying existing code.
- Flexible composition: Combine decorators in any order.
- Avoids class explosion: No need for a separate class for every possible combination (e.g.,
MilkSugarCoffee vs SugarMilkCoffee).
Common Use Cases:
- Python’s
@decorator syntax (function/method decorators).
- I/O streams (e.g.,
BufferedReader, GZIPOutputStream in Java).
- GUI components (adding scrollbars/borders to windows).
- Web frameworks (adding middleware/authentication).
Note:
Python’s built-in decorators (using @) are syntactic sugar for wrapping functions, but the pattern shown here applies to objects and is language-agnostic.