Decorator Pattern

Summary

  • The role of the Decorator pattern is to provide a way of attaching new state and behaviour to an object dynamically. The object does not know it is being "decorated", which makes this a useful pattern for evolving systems.
  • A key implementation point in the Decorator pattern is that decorators both inherit the original class and contain an instantiation of it. The client can use the original component and Decorator component interchangeably.
  • Each Decorator contains a component object, which might itself be a Decorator.
  • The Decorator pattern's key feature is that it does not rely on inheritance for extending behaviour.
  • Decorators do not need any advanced language features; they rely on object aggregation and interface implementation.
  • An important point about the Decorator pattern is that it is based around new objects being created with their own sets of operations. Some of these might be inherited, but only down one level.

Class diagram: (see Decorator Pattern code review)

Decorator Pattern class diagram of sample code download

Usage

Use the Decorator pattern when:

  • You have an existing component class that may be unavailable for subclassing.
  • You want to attach additional state or behaviour to an object dynamically.
  • You want to make changes to some objects in a class without affecting others.
  • Avoid subclassing because too many classes could result.