Chapter 5. The Decorator Pattern

Whenever we want to add extra functionality to an object, we have a number of different options. We can:

  • Add the functionality directly to the class the object belongs to, if it makes sense (for example, add a new method)
  • Use composition
  • Use inheritance

Composition should generally be preferred over inheritance, because inheritance makes code reuse harder, it's static, and applies to an entire class and all instances of it [GOF95, page 31], [j.mp/decopat].

Design patterns offer us a fourth option that supports extending the functionality of an object dynamically (in runtime): Decorators. A Decorator pattern can add responsibilities to an object dynamically, and in a transparent manner (without affecting other objects) ...

Get Python: Master the Art of Design Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.