Decorator

structural

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

Intent

The Decorator pattern attaches additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.

Motivation

Sometimes you want to add responsibilities to individual objects, not to an entire class. Inheritance isn't always flexible enough because it requires creating a new class for each combination of features. The Decorator pattern provides a flexible alternative.

Structure

The pattern involves a Component interface, ConcreteComponent that implements it, and Decorator classes that wrap the component and add new behavior.

Participants

  • Component - defines the interface for objects that can have responsibilities added to them
  • 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

Pros

  • More flexible than static inheritance
  • Avoids feature-laden classes high up in the hierarchy
  • Responsibilities can be added and removed at runtime
  • Follows Single Responsibility and Open/Closed Principles

Cons

  • Can result in many small objects
  • Can be complicated to configure
  • Decorators and their components are not identical

Use Cases

Adding scrolling to GUI components
Adding borders or styling to UI elements
Data stream processing (encryption, compression)
Adding features to coffee orders
Enhancing HTTP requests/responses

Implementation Tips

Considerations

  • Keep the Component interface simple
  • Decide on the decorator interface
  • Consider making decorators transparent
  • Think about the order of decoration

Tips

  • Use composition over inheritance
  • Keep decorators focused on a single responsibility
  • Consider using abstract decorator classes
  • Document the decoration order if it matters

Interactive Code Editor

Related Patterns