Design Patterns    |     Security    |     Testing    |     Distributed Computing    |     Contact

Decorator

Definition

Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.

Class Diagram

Decorator

Participants

  • Component.
    • defines the interface for objects that can have responsibilities added to them dynamically.
  • ConcreteComponent.
    • defines an object to which additional responsibilities can be attached.
  • Decorator.
    • maintains a reference to a Component object and defines an interface that conforms to Component's interface.
  • ConcreteDecorator.
    • adds responsibilities to the component.

Benefits

  • More flexibility than static inheritance.
  • Avoids feature-laedn 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.

Usage

  • When you want to add responsibilities to individual objects dinamically and transparently, without affecting other objects.
  • When you want to add responsibilities to the object that you might want to change in the future.
  • When extension by static subclassing is impractical.