Decorator Pattern in Python
Decorator wraps an object that follows the same interface and enhances its result.
What is Decorator Pattern?
Decorator wraps an object that follows the same interface and enhances its result.
Add behavior to an object dynamically without changing its class.
When should you use it?
- Solve recurring object-design problems with proven structures.
- Decouple responsibilities so code is easier to extend and test.
- Use shared design vocabulary when discussing architecture with a team.
Example code
main.py
class Message:
# Decorator: wrap an object to add behavior dynamically.
def render(self): return "hello"
class Uppercase:
def __init__(self, wrapped): self.wrapped = wrapped
def render(self): return self.wrapped.render().upper()
class Logger:
def __init__(self, wrapped): self.wrapped = wrapped
def render(self):
# Add behavior while preserving the render interface.
return "LOG: " + self.wrapped.render()
print(Logger(Uppercase(Message())).render())
Expected output
LOG: HELLO
How it works
Uppercase and Logger can be stacked around the original message object at runtime.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Replace the sample domain while preserving the pattern structure.
- Compare the pattern with a simpler implementation and explain the tradeoff.
- Write tests for each participant before adding another implementation.