The 23 GoF design patterns and Dependency Injection – choose a pattern Abstract Factory design patternBuilder design patternFactory Method design patternPrototype design patternSingleton design patternAdapter design patternBridge design patternComposite design patternDecorator design patternFacade design patternFlyweight design patternProxy design patternChain of Responsibility design patternCommand design patternInterpreter design patternIterator design patternMediator design patternMemento design patternObserver design patternState design patternStrategy design patternTemplate Method design patternVisitor design patternDependency Injection design pattern

Decorator Design Pattern

Structural pattern. Structural design patterns are concerned with composing classes and objects into larger structures.

The Decorator design pattern solves problems like: How can responsibilities be added to (and withdrawn from) an object dynamically?

Open in the interactive referenceDownload the PDF reference

Problem

The Decorator design pattern solves problems like:
How can responsibilities be added to an object dynamically?
How can the functionality of an object be extended at run-time?
See Applicability section for all problems Decorator can solve. See Solution section for how Decorator solves the problems.

  • Subclassing is the standard way to extend the functionality of (add responsibilities to) a class statically at compile-time.
    Once a subclass (Subclass1) is instantiated, the functionality is bound to the instance for its life-time and can't be changed at run-time.
  • That's the kind of approach to avoid if we want to extend the functionality of an object at run-time instead of extending the functionality of a class at compile-time.
  • For example, reusable GUI/Web objects (like buttons, menus, or tree widgets).
    It should be possible to add embellishments (i.e., borders, scroll bars, etc.) to basic GUI/Web objects dynamically at run-time.
  • For example, I/O data stream objects [Java Platform].
    It should be possible to add responsibilities like handling data types and buffered data to basic I/O objects that only handle raw binary data (see Sample Code / Example 2).
  • For example, collections [Java Collections Framework].
    It should be possible to add automatic synchronization (thread-safety) to a collection or taking away the ability to modify a collection.

Solution

The Decorator design pattern provides a solution:
Define separate Decorator objects that add responsibilities to an object.
Work through Decorator objects to extend the functionality of an object at run-time.
Describing the Decorator design in more detail is the theme of the following sections.
See Applicability section for all problems Decorator can solve.

  • The key idea in this pattern is to work through separate Decorator objects that 'decorate' (add responsibilities to) an (already existing) object.
    A decorator implements the Component interface transparently so that it can act as transparent enclosure of the component that gets decorated.
    "Clients gene­rally can't tell whether they're dealing with the component or its enclosure […]." [GoF, p44]
  • Define separate Decorator objects:
    • Define a class (Decorator) that maintains a reference to a Component object (component) and forwards requests to this component (component.operation()).
    • Define subclasses (Decorator1,…) that implement additional functionality (addBehavior()) to be performed before and/or after forwarding a request.
  • Because decorators are transparent enclosures of the decorated component, they can be nested recursively to add an open-ended number of responsibilities.
    Changing the order of decorators allows adding any combinations of responsibilities.
    In the above sequence diagram, for example, a client works through two nested decorator objects that add responsibilities to a Component1 object (after forwarding the request).

Applicability

Design Problems

  • Extending Functionality at Run-Time
    • How can responsibilities be added to (and withdrawn from) an object dynamically?
    • How can the functionality of an object be extended at run-time?
    • How can a simple class be defined that is extended at run-time
      instead of implementing all foreseeable functionality in a complex class?
  • Flexible Alternative to Subclassing
    • How can a flexible alternative be provided to subclassing
      for extending the functionality of a class at compile-time?

Refactoring Problems

  • Inflexible Code
    • How can classes that include hard-wired extensions (compile-time implementation dependencies) be refactored? Move Embellishment to Decorator (144) [JK05]

Structure

Static Class Structure

  • Client
    • Refers to the Component interface.
  • Component
    • Defines a common interface for Component1 and Decorator objects.
  • Component1
    • Defines objects that get decorated.
  • Decorator
    • Maintains a reference to a Component object (component).
    • Forwards requests to this component (component.operation()).
  • Decorator1,Decorator2,…
    • Implement additional functionality (addBehavior()) to be performed before and/or after forwarding a request.

Dynamic Object Collaboration

  • In this sample scenario, a Client object works through two decorators that add responsibilities to a Component1 object.
  • The Client calls operation() on the Decorator1 object.
  • Decorator1 forwards the request to the Decorator2 object.
  • Decorator2 forwards the request to the Component1 object.
  • Component1 performs the request and returns to Decorator2.
  • Decorator2 performs additional functionality (by calling addBehavior() on itself) and returns to Decorator1.
  • Decorator1 performs additional functionality and returns to the Client.
  • See also Sample Code / Example 1.

Sample Code 1

Basic Java code for implementing the sample UML diagrams.

 1  package com.sample.decorator.basic;
 2  public class Client { 
 3      // Running the Client class as application.
 4      public static void main(String[] args) { 
 5          // Working with the component directly.
 6          Component component = new Component1();
 7          System.out.println("(1) " + component.operation());
 8          // Working through decorators.
 9          component = new Decorator1(new Decorator2(component));
10          System.out.println("(2) " + component.operation());
11      } 
12  } 
(1) Hello World from Component1!
(2) *** === Hello World from Component1! === ***
 1  package com.sample.decorator.basic;
 2  public abstract class Component { 
 3      public abstract String operation();    
 4  } 

 1  package com.sample.decorator.basic;
 2  public class Component1 extends Component { 
 3      public String operation() { 
 4          return "Hello World from Component1!";
 5      } 
 6  } 

 1  package com.sample.decorator.basic;
 2  public abstract class Decorator extends Component { 
 3      Component component;
 4      public Decorator(Component component) { 
 5          this.component = component;
 6      } 
 7      public String operation() { 
 8          // Forwarding to component.
 9          return component.operation();
10      } 
11  } 

 1  package com.sample.decorator.basic;
 2  public class Decorator1 extends Decorator { 
 3      public Decorator1(Component component) { 
 4          super(component); // calling the super class constructor
 5      } 
 6      public String operation() { 
 7          // Forwarding to component.
 8          String result = super.operation();
 9          // Adding functionality to result from component.
10          return addBehavior(result);
11      } 
12      private String addBehavior(String result) { 
13          return "***" + result + "***";
14      } 
15  } 

 1  package com.sample.decorator.basic;
 2  public class Decorator2 extends Decorator { 
 3      public Decorator2(Component component) { 
 4          super(component); // calling the super class constructor
 5      } 
 6      public String operation() { 
 7          // Forwarding to component.
 8          String result = super.operation();
 9          // Adding functionality to result from component.
10          return addBehavior(result);
11      } 
12      private String addBehavior(String result) { 
13          return " === " + result + " === ";
14      } 
15  } 

Not included on this page: Intent, Motivation, Consequences, Implementation, Related Patterns. See the GoF Design Patterns Reference (PDF) for the complete description.