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
Decoratorobjects that 'decorate' (add responsibilities to) an (already existing) object.
A decorator implements theComponentinterface transparently so that it can act as transparent enclosure of the component that gets decorated.
"Clients generally can't tell whether they're dealing with the component or its enclosure […]." [GoF, p44] -
Define separate
Decoratorobjects:-
Define a class (
Decorator) that maintains a reference to aComponentobject (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.
-
Define a class (
-
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 aComponent1object (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?
-
How can a flexible alternative be provided to subclassing
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
Componentinterface.
-
Refers to the
-
Component-
Defines a common interface for
Component1andDecoratorobjects.
-
Defines a common interface for
-
Component1- Defines objects that get decorated.
-
Decorator-
Maintains a reference
to a
Componentobject (component). -
Forwards requests to this component
(
component.operation()).
-
Maintains a reference
to a
-
Decorator1,Decorator2,…-
Implement additional functionality
(
addBehavior()) to be performed before and/or after forwarding a request.
-
Implement additional functionality
(
Dynamic Object Collaboration
-
In this sample scenario,
a
Clientobject works through two decorators that add responsibilities to aComponent1object. -
The
Clientcallsoperation()on theDecorator1object. -
Decorator1forwards the request to theDecorator2object. -
Decorator2forwards the request to theComponent1object. -
Component1performs the request and returns toDecorator2. -
Decorator2performs additional functionality (by callingaddBehavior()on itself) and returns toDecorator1. -
Decorator1performs additional functionality and returns to theClient. -
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.