Decorator

Category

Structural pattern

Problem

Add responsibilities to individual objects dynamically and transparently, without affecting other objects. An alternative to subclassing for adding functionality.

Solution

  • Wrap the original object in a decorator class that implements the same interface
  • The decorator delegates to the wrapped object, adding behavior before or after the delegation
  • Multiple decorators can be chained to add multiple behaviors

Structure

  • Component: Interface for objects that can have responsibilities added
  • ConcreteComponent: The object being decorated
  • Decorator: Decorator base class; holds a reference to a Component
  • ConcreteDecorator: Adds responsibilities to the Component

Key Benefits

  • Dynamic behavior addition — Add/remove responsibilities at runtime
  • Open/Closed Principle — New decorators can be added without modifying existing code
  • Composability — Multiple decorators can be stacked for combined behavior

Trade-offs

  • Many small objects — Can create a proliferation of decorator classes
  • Configuration complexity — Chaining many decorators can be hard to configure

When to Use

  • You want to add responsibilities to individual objects dynamically without affecting other objects
  • Subclassing is impractical (e.g., too many possible combinations of behavior)
  • You need to be able to撤销 (remove) responsibilities

Examples