Decorator Pattern

The Decorator pattern enables you to add or remove object functionality without changing the external appearance or function of the object. It changes the functionality of an object in a way that is transparent to its clients by using an instance of a subclass of the original class that delegates operations to the original object. The Decorator pattern
attaches additional responsibilities to an object dynamically to provide a flexible alternative to changing object functionality without using static inheritance. 

UML representation


The following lists the benefits of using the Decorator pattern:
  • More flexibility than static inheritance
  • Avoids feature-laden classes high up in the hierarchy
  • Simplifies coding because you write a series of classes, each targeted at a specific part of the functionality, rather than coding all behavior into the object
  • Enhances the object’s extensibility because you make changes by coding new classes

When to Use

You should use the Decorator pattern when:
  • You want to add responsibilities to individual objects dynamically and transparently—that is, without affecting other objects.
  • You want to add responsibilities to the object that you might want to change in the future.
  • Extension by static subclassing is impractical.