Decorator pattern

From Wikipedia, the free encyclopedia
Jump to: navigation, search
Not to be confused with the concept of "decorators" in Python.

In object-oriented programming, the decorator pattern (also known as Wrapper, an alternative naming shared with the Adapter pattern) is a design pattern that allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class.[1]

Intent[edit]

Decorator UML class diagram

The decorator pattern can be used to extend (decorate) the functionality of a certain object statically, or in some cases at run-time, independently of other instances of the same class, provided some groundwork is done at design time. This is achieved by designing a new decorator class that wraps the original class. This wrapping could be achieved by the following sequence of steps:

  1. Subclass the original "Component" class into a "Decorator" class (see UML diagram);
  2. In the Decorator class, add a Component pointer as a field;
  3. Pass a Component to the Decorator constructor to initialize the Component pointer;
  4. In the Decorator class, redirect all "Component" methods to the "Component" pointer; and
  5. In the ConcreteDecorator class, override any Component method(s) whose behavior needs to be modified.

This pattern is designed so that multiple decorators can be stacked on top of each other, each time adding a new functionality to the overridden method(s).

Note that decorators and the original class object share a common set of features. In the previous diagram, the "operation()" method was available in both the decorated and undecorated versions.

The decoration features (e.g., methods, properties, or other members) are usually defined by an interface, mixin (a.k.a. "trait") or class inheritance which is shared by the decorators and the decorated object. In the previous example the class "Component" is inherited by both the "ConcreteComponent" and the subclasses that descend from "Decorator".

The decorator pattern is an alternative to subclassing. Subclassing adds behavior at compile time, and the change affects all instances of the original class; decorating can provide new behavior at run-time for individual objects.

This difference becomes most important when there are several independent ways of extending functionality. In some object-oriented programming languages, classes cannot be created at runtime, and it is typically not possible to predict, at design time, what combinations of extensions will be needed. This would mean that a new class would have to be made for every possible combination. By contrast, decorators are objects, created at runtime, and can be combined on a per-use basis. The I/O Streams implementations of both Java and the .NET Framework incorporate the decorator pattern.

Motivation[edit]

UML diagram for the window example

As an example, consider a window in a windowing system. To allow scrolling of the window's contents, one may wish to add horizontal or vertical scrollbars to it, as appropriate. Assume windows are represented by instances of the Window class, and assume this class has no functionality for adding scrollbars. One could create a subclass ScrollingWindow that provides them, or create a ScrollingWindowDecorator that adds this functionality to existing Window objects. At this point, either solution would be fine.

Now, assume one also desires the ability to add borders to windows. Again, the original Window class has no support. The ScrollingWindow subclass now poses a problem, because it has effectively created a new kind of window. If one wishes to add border support to many but not all windows, one must create subclasses WindowWithBorder and ScrollingWindowWithBorder etc. This problem gets worse with every new feature or window subtype to be added. For the decorator solution, we simply create a new BorderedWindowDecorator—at runtime, we can decorate existing windows with the ScrollingWindowDecorator or the BorderedWindowDecorator or both, as we see fit. Notice that if the functionality needs to be added to all Windows, you could modify the base class and that will do. On the other hand, sometimes (e.g., using external frameworks) it is not possible, legal, or convenient to modify the base class.

Note, in the previous example, that the "SimpleWindow" and "WindowDecorator" classes implement the "Window" interface, which defines the "draw()" method and the "getDescription()" method, that are required in this scenario, in order to decorate a window control.

Examples[edit]

Java[edit]

First example (window/scrolling scenario)[edit]

The following Java example illustrates the use of decorators using the window/scrolling scenario.

// The Window interface class
public interface Window {
    public void draw(); // Draws the Window
    public String getDescription(); // Returns a description of the Window
}
 
// Extension of a simple Window without any scrollbars
class SimpleWindow implements Window {
    public void draw() {
        // Draw window
    }
 
    public String getDescription() {
        return "simple window";
    }
}

The following classes contain the decorators for all Window classes, including the decorator classes themselves.

// abstract decorator class - note that it implements Window
abstract class WindowDecorator implements Window {
    protected Window windowToBeDecorated; // the Window being decorated
 
    public WindowDecorator (Window windowToBeDecorated) {
        this.windowToBeDecorated = windowToBeDecorated;
    }
    public void draw() {
        windowToBeDecorated.draw(); //Delegation
    }
    public String getDescription() {
        return windowToBeDecorated.getDescription(); //Delegation
    }
}
 
// The first concrete decorator which adds vertical scrollbar functionality
class VerticalScrollBarDecorator extends WindowDecorator {
    public VerticalScrollBarDecorator (Window windowToBeDecorated) {
        super(windowToBeDecorated);
    }
 
    @Override
    public void draw() {
        super.draw();
        drawVerticalScrollBar();
    }
 
    private void drawVerticalScrollBar() {
        // Draw the vertical scrollbar
    }
 
    @Override
    public String getDescription() {
        return super.getDescription() + ", including vertical scrollbars";
    }
}
 
// The second concrete decorator which adds horizontal scrollbar functionality
class HorizontalScrollBarDecorator extends WindowDecorator {
    public HorizontalScrollBarDecorator (Window windowToBeDecorated) {
        super(windowToBeDecorated);
    }
 
    @Override
    public void draw() {
        super.draw();
        drawHorizontalScrollBar();
    }
 
    private void drawHorizontalScrollBar() {
        // Draw the horizontal scrollbar
    }
 
    @Override
    public String getDescription() {
        return super.getDescription() + ", including horizontal scrollbars";
    }
}

Here's a test program that creates a Window instance which is fully decorated (i.e., with vertical and horizontal scrollbars), and prints its description:

public class DecoratedWindowTest {
    public static void main(String[] args) {
        // Create a decorated Window with horizontal and vertical scrollbars
        Window decoratedWindow = new HorizontalScrollBarDecorator (
                new VerticalScrollBarDecorator (new SimpleWindow()));
 
        // Print the Window's description
        System.out.println(decoratedWindow.getDescription());
    }
}

The output of this program is "simple window, including vertical scrollbars, including horizontal scrollbars". Notice how the getDescription method of the two decorators first retrieve the decorated Window's description and decorates it with a suffix.

Second example (coffee making scenario)[edit]

The next Java example illustrates the use of decorators using coffee making scenario. In this example, the scenario only includes cost and ingredients.

// The abstract Coffee class defines the functionality of Coffee implemented by decorator
public abstract class Coffee {
    public abstract double getCost(); // Returns the cost of the coffee
    public abstract String getIngredients(); // Returns the ingredients of the coffee
}
 
// Extension of a simple coffee without any extra ingredients
public class SimpleCoffee extends Coffee {
    public double getCost() {
        return 1;
    }
 
    public String getIngredients() {
        return "Coffee";
    }
}

The following classes contain the decorators for all Coffee classes, including the decorator classes themselves..

// Abstract decorator class - note that it extends Coffee abstract class
public abstract class CoffeeDecorator extends Coffee {
    protected final Coffee decoratedCoffee;
    protected String ingredientSeparator = ", ";
 
    public CoffeeDecorator (Coffee decoratedCoffee) {
        this.decoratedCoffee = decoratedCoffee;
    }
 
    public double getCost() { // Implementing methods of the abstract class
        return decoratedCoffee.getCost();
    }
 
    public String getIngredients() {
        return decoratedCoffee.getIngredients();
    }
}
 
// Decorator Milk that mixes milk with coffee.
// Note it extends CoffeeDecorator.
class Milk extends CoffeeDecorator {
    public Milk (Coffee decoratedCoffee) {
        super(decoratedCoffee);
    }
 
    public double getCost() { // Overriding methods defined in the abstract superclass
        return super.getCost() + 0.5;
    }
 
    public String getIngredients() {
        return super.getIngredients() + ingredientSeparator + "Milk";
    }
}
 
// Decorator Whip that mixes whip with coffee.
// Note it extends CoffeeDecorator.
class Whip extends CoffeeDecorator {
    public Whip (Coffee decoratedCoffee) {
        super(decoratedCoffee);
    }
 
    public double getCost() {
        return super.getCost() + 0.7;
    }
 
    public String getIngredients() {
        return super.getIngredients() + ingredientSeparator + "Whip";
    }
}
 
// Decorator Sprinkles that mixes sprinkles with coffee.
// Note it extends CoffeeDecorator.
class Sprinkles extends CoffeeDecorator {
    public Sprinkles (Coffee decoratedCoffee) {
        super(decoratedCoffee);
    }
 
    public double getCost() {
        return super.getCost() + 0.2;
    }
 
    public String getIngredients() {
        return super.getIngredients() + ingredientSeparator + "Sprinkles";
    }
}

Here's a test program that creates a Coffee instance which is fully decorated (i.e., with milk, whip, sprinkles), and calculate cost of coffee and prints its ingredients:

public class Main {
 
    public static final void main(String[] args) {
	Coffee c = new SimpleCoffee();
	System.out.println("Cost: " + c.getCost() + "; Ingredients: " + c.getIngredients());
 
	c = new Milk(c);
	System.out.println("Cost: " + c.getCost() + "; Ingredients: " + c.getIngredients());
 
	c = new Sprinkles(c);
	System.out.println("Cost: " + c.getCost() + "; Ingredients: " + c.getIngredients());
 
	c = new Whip(c);
	System.out.println("Cost: " + c.getCost() + "; Ingredients: " + c.getIngredients());
 
	// Note that you can also stack more than one decorator of the same type
	c = new Sprinkles(c);
	System.out.println("Cost: " + c.getCost() + "; Ingredients: " + c.getIngredients());
    }
 
}

The output of this program is given below:

Cost: 1.0; Ingredients: Coffee
Cost: 1.5; Ingredients: Coffee, Milk
Cost: 1.7; Ingredients: Coffee, Milk, Sprinkles
Cost: 2.4; Ingredients: Coffee, Milk, Sprinkles, Whip
Cost: 2.6; Ingredients: Coffee, Milk, Sprinkles, Whip, Sprinkles

C++[edit]

Here is an example program written in C++:

#include <iostream>
#include <string>
 
/* Abstract base class */
// The abstract Coffee class defines the functionality of Coffee implemented by decorator
struct Coffee {
  virtual double getCost() = 0; // Returns the cost of the coffee
  virtual std::string getIngredients() = 0; // Returns the ingredients of the coffee
  virtual ~Coffee() = 0;
};
inline Coffee::~Coffee() { }
 
/* SimpleCoffee class. */
// Extension of a simple coffee without any extra ingredients
struct SimpleCoffee : public Coffee {
  virtual double getCost() {
    return 1.0;
  }
 
  virtual std::string getIngredients() {
    return "Coffee";
  }
};
 
/* Decorators */
// Decorator Milk that adds milk to coffee.
struct MilkDecorator : Coffee {
  MilkDecorator (Coffee *basicCoffee)
    : basicCoffee(basicCoffee) {
  }
 
  virtual double getCost() { // Providing methods defined in the abstract superclass
    return basicCoffee->getCost() + 0.5;
  }
 
  virtual std::string getIngredients() {
    return basicCoffee->getIngredients() + ", " + "Milk";
  }
private:
  Coffee *basicCoffee;
};
 
// Decorator Whip that adds whip to coffee
struct WhipDecorator : Coffee {
  WhipDecorator (Coffee *basicCoffee)
    : basicCoffee(basicCoffee) {
  }
 
  virtual double getCost() {
    return basicCoffee->getCost() + 0.7;
  }
 
  virtual std::string getIngredients() {
    return basicCoffee->getIngredients() + ", " + "Whip";
  }
private:
  Coffee *basicCoffee;
};
 
/* Test program */
int main() 
{
  SimpleCoffee s;
  std::cout << "Cost: " << s.getCost() << "; Ingredients: " << s.getIngredients() << std::endl;
 
  MilkDecorator m(&s);
  std::cout << "Cost: " << m.getCost() << "; Ingredients: " << m.getIngredients() << std::endl;
 
  WhipDecorator w(&s);
  std::cout << "Cost: " << w.getCost() << "; Ingredients: " << w.getIngredients() << std::endl;
 
  // Note that you can stack decorators:
  MilkDecorator m2(&w);
  std::cout << "Cost: " << m2.getCost() << "; Ingredients: " << m2.getIngredients() << std::endl;
}

The output of this program is given below:

Cost: 1.0; Ingredients: Coffee
Cost: 1.5; Ingredients: Coffee, Milk
Cost: 1.7; Ingredients: Coffee, Whip
Cost: 2.2; Ingredients: Coffee, Whip, Milk

Dynamic languages[edit]

The decorator pattern can also be implemented in dynamic languages either with interfaces or with traditional OOP inheritance.

See also[edit]

References[edit]

  1. ^ Gamma, et al., Erich (1995). Design Patterns. Reading, MA: Addison-Wesley Publishing Co, Inc. pp. 175ff. ISBN 0-201-63361-2. 

External links[edit]