Decorator pattern: Difference between revisions
Codysnider (talk | contribs) m Link is valid |
|||
Line 371: | Line 371: | ||
* [http://www.lukeredpath.co.uk/2006/9/6/decorator-pattern-with-ruby-in-8-lines Decorator Pattern with Ruby in 8 Lines] (Ruby) |
* [http://www.lukeredpath.co.uk/2006/9/6/decorator-pattern-with-ruby-in-8-lines Decorator Pattern with Ruby in 8 Lines] (Ruby) |
||
* [http://perfectjpattern.sourceforge.net/dp-decorator.html PerfectJPattern Open Source Project], Provides componentized implementation of the Decorator Pattern in Java |
* [http://perfectjpattern.sourceforge.net/dp-decorator.html PerfectJPattern Open Source Project], Provides componentized implementation of the Decorator Pattern in Java |
||
* [http://www.patternizando.com.br/2011/01/padrao-de-projeto-decorator-uma-aplicacao-real-em-java/] Portugues implementation example |
|||
{{Design Patterns Patterns}} |
{{Design Patterns Patterns}} |
Revision as of 17:16, 28 January 2011
In object-oriented programming, the decorator pattern is a design pattern that allows new/additional behaviour to be added to an existing object dynamically.
Introduction
The decorator pattern can be used to make it possible to extend (decorate) the functionality of a certain object at runtime, 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:
- Subclass the original "Component" class into a "Decorator" class (see UML diagram);
- In the Decorator class, add a Component pointer as a field;
- Pass a Component to the Decorator constructor to initialize the Component pointer;
- In the Decorator class, redirect all "Component" methods to the "Component" pointer; and
- 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).
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 runtime 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
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 desire the ability 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.
Examples
Java
First Example (window/scrolling scenario)
The following Java example illustrates the use of decorators using the window/scrolling scenario.
// 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;
}
public void draw() {
decoratedWindow.draw();
}
}
// the first concrete decorator which adds vertical scrollbar functionality
class VerticalScrollBarDecorator extends WindowDecorator {
public VerticalScrollBarDecorator (Window decoratedWindow) {
super(decoratedWindow);
}
public void draw() {
drawVerticalScrollBar();
super.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();
super.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.
Second Example (coffee making scenario)
The next Java example illustrates the use of decorators using coffee making scenario. In this example, the scenario only includes cost and ingredients.
//The Coffee Interface defines the functionality of Coffee implemented by decorator
public interface Coffee
{
public double getCost(); // returns the cost of coffee
public String getIngredient(); //returns the ingredients mixed with coffee
}
//implementation of simple coffee without any extra ingredients
public class SimpleCoffee implements Coffee
{
double cost;
String ingredient;
public SimpleCoffee()
{
cost = 1;
ingredient = "Coffee";
}
public double getCost()
{
return cost;
}
public String getIngredient()
{
return ingredient;
}
}
The following classes contain the decorators for all Coffee classes, including the decorator classes themselves..
//abstract decorator class - note that it implements coffee interface
abstract public class CoffeeDecorator implements Coffee
{
protected Coffee decoratedCoffee;
protected String ingredientSeparator;
public CoffeeDecorator(Coffee decoratedCoffee)
{
this.decoratedCoffee = decoratedCoffee;
ingredientSeparator = ", ";
}
public double getCost() //note it implements the getCost function defined in interface Coffee
{
return decoratedCoffee.getCost();
}
public String getIngredient()
{
return decoratedCoffee.getIngredient();
}
}
//Decorator Milk that mixes milk with coffee
//note it extends CoffeeDecorator
public class Milk extends CoffeeDecorator
{
double cost;
String ingredient;
public Milk(Coffee decoratedCoffee)
{
super(decoratedCoffee);
cost = 0.5;
ingredient = "Milk";
}
public double getCost()
{
return super.getCost() + cost;
}
public String getIngredient()
{
return super.getIngredient() + super.ingredientSeparator + ingredient;
}
}
//Decorator Whip that mixes whip with coffee
//note it extends CoffeeDecorator
public class Whip extends CoffeeDecorator
{
double cost;
String ingredient;
public Whip(Coffee decoratedCoffee)
{
super(decoratedCoffee);
cost = 0.7;
ingredient = "Whip";
}
public double getCost()
{
return super.getCost() + cost;
}
public String getIngredient()
{
return super.getIngredient() + super.ingredientSeparator + ingredient;
}
}
//Decorator Sprinkles that mixes sprinkles with coffee
//note it extends CoffeeDecorator
public class Sprinkles extends CoffeeDecorator
{
double cost;
String ingredient;
public Sprinkles(Coffee decoratedCoffee)
{
super(decoratedCoffee);
cost = 0.2;
ingredient = "Sprinkles";
}
public double getCost()
{
return super.getCost() + cost;
}
public String getIngredient()
{
return super.getIngredient() + super.ingredientSeparator + ingredient;
}
}
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 void main(String[] args)
{
Coffee sampleCoffee = new SimpleCoffee();
System.out.println("Cost: " + sampleCoffee.getCost() + " Ingredient: " + sampleCoffee.getIngredient());
sampleCoffee = new Milk(sampleCoffee);
System.out.println("Cost: " + sampleCoffee.getCost() + " Ingredient: " + sampleCoffee.getIngredient());
sampleCoffee = new Sprinkles(sampleCoffee);
System.out.println("Cost: " + sampleCoffee.getCost() + " Ingredient: " + sampleCoffee.getIngredient());
sampleCoffee = new Whip(sampleCoffee);
System.out.println("Cost: " + sampleCoffee.getCost() + " Ingredient: " + sampleCoffee.getIngredient());
}
}
The output of this program is given below:
Cost: 1.0 Ingredient: Coffee
Cost: 1.5 Ingredient: Coffee, Milk
Cost: 1.7 Ingredient: Coffee, Milk, Sprinkles
Cost: 2.4 Ingredient: Coffee, Milk, Sprinkles, Whip
Dynamic languages
The decorator pattern can also be implemented in dynamic languages with neither interfaces nor traditional OOP inheritance.
JavaScript (coffee making scenario)
// 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());
See also
- Composite pattern
- Adapter pattern
- Abstract class
- Abstract factory
- Aspect-oriented programming
- Immutable object
External links
- Decorator Pattern UML and Code Example
- 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)
- A Delphi approach (Delphi)
- A JavaScript implementation
- Decorator Pattern with Ruby in 8 Lines (Ruby)
- PerfectJPattern Open Source Project, Provides componentized implementation of the Decorator Pattern in Java
- [1] Portugues implementation example