Decorator pattern
From Wikipedia, the free encyclopedia
In object-oriented programming, the decorator pattern is a design pattern that allows new/additional behaviour to be added to an existing class dynamically.
Contents |
[edit] Introduction
The decorator pattern can be used to make it possible to extend (decorate) the functionality of a class at runtime. This works by adding a new decorator class that wraps the original class. This wrapping is achieved by
- Subclass the original "Component" class into a "Decorator" class (see UML diagram)
- In class Decorator, add a Component pointer as a field
- Pass a Decorator pointer to the Decorator constructor to initialize the Component pointer.
- In class Decorator, redirect all "Component" methods to the "Component" pointer. This implies that all Decorator fields coming from the Component motherclass will never be used and their memory space will be wasted. That is an accepted drawback of the decorator pattern.
- In class Decorator, override any Component method which 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.
The decorator pattern is an alternative to subclassing. Subclassing adds behavior at compile time whereas decorating can provide new behaviour at runtime.
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 what combinations of extensions will be needed at design time. 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. An example of the decorator pattern is the Java I/O Streams implementation.
[edit] Motivation
As an example, consider a window in a windowing system. To allow scrolling of the window's contents, we 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. We could create a subclass ScrollingWindow that provides them, or we could create a ScrollingWindowDecorator that adds this functionality to existing Window objects. At this point, either solution would be fine.
Now let's assume we also wish the option to add borders to our windows. Again, our original Window class has no support. The ScrollingWindow subclass now poses a problem, because it has effectively created a new kind of window. If we wish to add border support to all windows, we must create subclasses WindowWithBorder and ScrollingWindowWithBorder. Obviously, this problem gets worse with every new feature 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.
Another good example of where a decorator can be desired is when there is a need to restrict access to an object's properties or methods according to some set of rules or perhaps several parallel sets of rules (different user credentials, etc.) In this case instead of implementing the access control in the original object it is left unchanged and unaware of any restrictions on its use, and it is wrapped in an access control decorator object, which can then serve only the permitted subset of the original object's interface.
[edit] Code examples
The following examples illustrate the use of decorators using the window/scrolling scenario.
[edit] Java
// the Window interface interface Window { public void draw(); // draws the Window public String getDescription(); // returns a description of the Window } // implementation 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 decoratedWindow; // the Window being decorated public WindowDecorator (Window decoratedWindow) { this.decoratedWindow = decoratedWindow; } } // the first concrete decorator which adds vertical scrollbar functionality class VerticalScrollBarDecorator extends WindowDecorator { public VerticalScrollBarDecorator (Window decoratedWindow) { super(decoratedWindow); } public void draw() { drawVerticalScrollBar(); decoratedWindow.draw(); } private void drawVerticalScrollBar() { // draw the vertical scrollbar } public String getDescription() { return decoratedWindow.getDescription() + ", including vertical scrollbars"; } } // the second concrete decorator which adds horizontal scrollbar functionality class HorizontalScrollBarDecorator extends WindowDecorator { public HorizontalScrollBarDecorator (Window decoratedWindow) { super(decoratedWindow); } public void draw() { drawHorizontalScrollBar(); decoratedWindow.draw(); } private void drawHorizontalScrollBar() { // draw the horizontal scrollbar } public String getDescription() { return decoratedWindow.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.
[edit] C++
#include <iostream> using namespace std; /* Component (interface) */ class Widget { public: virtual void draw() = 0; virtual ~Widget() {} }; /* ConcreteComponent */ class TextField : public Widget { private: int width, height; public: TextField( int w, int h ){ width = w; height = h; } void draw() { cout << "TextField: " << width << ", " << height << endl; } }; /* Decorator (interface) */ class Decorator : public Widget { private: Widget* wid; // reference to Widget public: Decorator( Widget* w ) { wid = w; } void draw() { wid->draw(); } ~Decorator() { delete wid; } }; /* ConcreteDecoratorA */ class BorderDecorator : public Decorator { public: BorderDecorator( Widget* w ) : Decorator( w ) { } void draw() { Decorator::draw(); cout << " BorderDecorator" << endl; } }; /* ConcreteDecoratorB */ class ScrollDecorator : public Decorator { public: ScrollDecorator( Widget* w ) : Decorator( w ) { } void draw() { Decorator::draw(); cout << " ScrollDecorator" << endl; } }; int main( void ) { Widget* aWidget = new BorderDecorator( new ScrollDecorator( new TextField( 80, 24 ))); aWidget->draw(); delete aWidget; }
[edit] C#
namespace GSL_Decorator_pattern { interface IWindowObject { void Draw(); // draws the object String GetDescription(); // returns a description of the object } class ControlComponent : IWindowObject { public ControlComponent() { } public void Draw() // draws the object { Console.WriteLine("ControlComponent::draw()"); } public String GetDescription() // returns a description of the object { return "ControlComponent::getDescription()"; } } abstract class Decorator : IWindowObject { protected IWindowObject _decoratedWindow = null; // the object being decorated public Decorator(IWindowObject decoratedWindow) { _decoratedWindow = decoratedWindow; } public virtual void Draw() { _decoratedWindow.Draw(); Console.WriteLine("\tDecorator::draw() "); } public virtual String GetDescription() // returns a description of the object { return _decoratedWindow.GetDescription() + "\n\t" + "Decorator::getDescription() "; } } // the first decorator class DecorationA : Decorator { public DecorationA(IWindowObject decoratedWindow) : base(decoratedWindow) { } public override void Draw() { base.Draw(); DecorationAStuff(); } private void DecorationAStuff() { Console.WriteLine("\t\tdoing DecorationA things"); } public override String GetDescription() { return base.GetDescription() + "\n\t\tincluding " + this.ToString(); } }// end class ConcreteDecoratorA : Decorator class DecorationB : Decorator { public DecorationB(IWindowObject decoratedWindow) : base(decoratedWindow) { } public override void Draw() { base.Draw(); DecorationBStuff(); } private void DecorationBStuff() { Console.WriteLine("\t\tdoing DecorationB things"); } public override String GetDescription() { return base.GetDescription() + "\n\t\tincluding " + this.ToString(); } }// end class DecorationB : Decorator class DecorationC : Decorator { public DecorationC(IWindowObject decoratedWindow) : base(decoratedWindow) { } public override void Draw() { base.Draw(); DecorationCStuff(); } private void DecorationCStuff() { Console.WriteLine("\t\tdoing DecorationC things"); } public override String GetDescription() { return base.GetDescription() + "\n\t\tincluding " + this.ToString(); } }// end class DecorationC : Decorator class Program { static void Main(string[] args) { IWindowObject window = new DecorationA(new ControlComponent()); window = new DecorationB(window); window = new DecorationC(window); window.Draw(); window.GetDescription(); Console.ReadLine(); } } }// end of namespace GSL_Decorator_pattern
[edit] Python
class Coffee: def cost(self): return 1 class Milk: def __init__(self, coffee): self.coffee = coffee def cost(self): return self.coffee.cost() + .5 class Whip: def __init__(self, coffee): self.coffee = coffee def cost(self): return self.coffee.cost() + .7 class Sprinkles: def __init__(self, coffee): self.coffee = coffee def cost(self): return self.coffee.cost() + .2 # Example 1 coffee = Milk(Coffee()) print "Coffee with milk : "+str(coffee.cost()) # Example 2 coffee = Sprinkles(Whip(Milk(Coffee()))) print "Coffee with milk, whip and sprinkles : "+str(coffee.cost())
[edit] PHP
// Component interface MenuItem{ public function cost(); } // Concrete Component class Coffee implements MenuItem{ private $_cost = 1.00; public function cost(){ return $this->_cost; } } // Decorator abstract class MenuDecorator extends Coffee{ protected $_component; public function __construct(MenuItem $component){ $this->_component = $component; } } // Concrete Decorator class CoffeeMilkDecorator extends MenuDecorator{ public function cost(){ return $this->_component->cost() + 0.5; } } // Concrete Decorator class CoffeeWhipDecorator extends MenuDecorator{ public function cost(){ return $this->_component->cost() + 0.7; } } // Concrete Decorator class CoffeeSprinklesDecorator extends MenuDecorator{ public function cost(){ return $this->_component->cost() + 0.2; } } // Example 1 $coffee = new CoffeeMilkDecorator(new Coffee()); print "Coffee with milk : ".$coffee->cost(); // Example 2 $coffee = new CoffeeWhipDecorator(new CoffeeMilkDecorator(new CoffeeSprinklesDecorator(new Coffee()))); print "Coffee with milk, whip and sprinkles : ".$coffee->cost();
[edit] Dynamic Languages
The decorator pattern can also be implemented in dynamic languages with no interfaces or traditional OOP inheritance.
JavaScript coffee shop:
//Class to be decorated function Coffee(){ this.cost = function(){ return 1; }; } //Decorator A function Milk(coffee){ this.cost = function(){ return coffee.cost() + 0.5; }; } //Decorator B function Whip(coffee){ this.cost = function(){ return coffee.cost() + 0.7; }; } //Decorator C function Sprinkles(coffee){ this.cost = function(){ return coffee.cost() + 0.2; }; } //Here's one way of using it var coffee = new Milk(new Whip(new Sprinkles(new Coffee()))); alert( coffee.cost() ); //Here's another var coffee = new Coffee(); coffee = new Sprinkles(coffee); coffee = new Whip(coffee); coffee = new Milk(coffee); alert(coffee.cost());
[edit] See also
[edit] External links
- Decorator pattern description from the Portland Pattern Repository
- Article "The Decorator Design Pattern" (Java) by Antonio García and Stephen Wong
- Article "Using the Decorator Pattern" (Java) by Budi Kurniawan
- Decorator in UML and in LePUS3 (a formal modelling language)
- Sample Chapter "C# Design Patterns: The Decorator Pattern" (C#) by James W. Cooper
- A PHP approach (PHP)
- A Delphi approach (Delphi)
- A JavaScript implementation
- Jt J2EE Pattern Oriented Framework
- Decorator Pattern with Ruby in 8 Lines (Ruby)
- PerfectJPattern Open Source Project, Provides componentized implementation of the Decorator Pattern in Java
|