Decorator (Wrapper - Smart Proxy) Pattern

Code Example

Code Structure

  1. The Component declares the common interface for both wrappers and wrapped objects.
  2. Concrete Component is a class of objects being wrapped. It defines the basic behavior, which can be altered by decorators.
  3. The Base Decorator class has a field for referencing a wrapped object. The field’s type should be declared as the component interface so it can contain both concrete components and decorators. The base decorator delegates all operations to the wrapped object.
  4. Concrete Decorators define extra behaviors that can be added to components dynamically. Concrete decorators override the methods of the base decorator and execute their behavior either before or after calling the parent method.
  5. The Client can wrap components in multiple layers of decorators, as long as it works with all objects via the component interface.

Applicability

Decorator is used to:

  • Add responsibilities to individual objects dynamically and transparently, that is, without affecting other objects.
  • For responsibilities that can be withdrawn.
  • When extension by subclassing is impractical. Sometimes a large number of independent extensions are possible and would produce an explosion of subclasses to support every combination. Or a class definition may be hidden or otherwise unavailable for subclassing.

Comparisons

Resources