FACTOID # 18: Sick of crowds? Move to Greenland! Greenlanders have 38 square kilometres of land per person.
 
 Home   Encyclopedia   Statistics   Countries A-Z   Flags   Maps   Education   Forum   FAQ   About 
 
 
 
WHAT'S NEW
RECENT ARTICLES
More Recent Articles »
 

SEARCH ALL

FACTS & STATISTICS    Advanced view

Search encyclopedia, statistics and forums:

 

 

(* = Graphable)

 

 


Encyclopedia > Decorator pattern

In object-oriented programming, the decorator pattern is a design pattern that allows new/additional behaviour to be added to an existing class dynamically. The syntax of the Python programming language is the set of rules that defines how a Python program will be written and interpreted (by both the runtime system and by human readers). ... Object-oriented programming (OOP) is a programming paradigm that uses objects and their interactions to design applications and computer programs. ... In software engineering, a design pattern is a general reusable solution to a commonly occurring problem in software design. ...

UML Class diagram of the decorator pattern
LePUS3 chart of the decorator pattern
LePUS3 chart of the decorator pattern

Contents

Image File history File links Decorator_Pattern_ZP.svg‎ UML diagram describing the Decorator Pattern. ... Image File history File links Decorator_Pattern_ZP.svg‎ UML diagram describing the Decorator Pattern. ... In the field of software engineering, the Unified/Universal Modeling Language (UML) is a standardized visual specification language for object modeling. ...

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 typically achieved by passing the original object as a parameter to the constructor of the decorator when it is created. The decorator implements the new functionality, but for functionality that is not new, the original (wrapped) class is used. The decorating class must have the same interface as the original class. In computer programming, the adapter design pattern (sometimes referred to as the wrapper pattern) adapts one interface for a class into one that a client expects. ...


The decorator pattern is an alternative to subclassing. Subclassing adds behaviour at compile time whereas decorating can provide new behaviour at runtime. In object-oriented programming, a subclass is a class that inherits some properties from its superclass. ... In computer science, compile time, as opposed to runtime, is the time when a compiler compiles code written in a programming language into an executable form. ... In computer science, runtime or run time describes the operation of a computer program, the duration of its execution, from beginning to termination (compare compile time). ...


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. An object-oriented programming language (also called an OO language) is one that allows or encourages, to some degree, object-oriented programming techniques such as encapsulation, inheritance, interfaces, and polymorphism. ... In object-oriented programming, a class consists of encapsulated instance variables and subprograms, the methods mentioned below. ... Java Platform, Standard Edition or Java SE (formerly known up to version 5. ...


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 merely adds this functionality to existing Window objects. At this point, either solution would be fine. A windowing system is a graphical user interface (GUI) which uses the window as one of its primary metaphors. ... This article needs cleanup. ... A scrollbar, or slider, is a graphical widget in a GUI with which continuous text, pictures or anything else can be scrolled including time in video applications, i. ... In computer programming a window class is a structure fundamental to the Microsoft Windows (Win16 and Win32) operating systems and its Application Programming Interface (API). ...


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 need merely 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.


Applicability

Consider viewing a webpage with a web browser. The webpage itself displays the information needed, but the web browser knows nothing about the content. It is likely that the webpage doesn't fit in the entire browser area and a scrollbar is required to show the information. The web browser doesn't need to assume that all webpages will require a scrollbar and it certainly should never assume a scrollbar is never needed. Browsers will typically display the scrollbar only if it is necessary and hide it if it is unnecessary. In this case, the scrollbar is the "decoration" to the webpage. It takes care of whether it should be displayed dynamically as opposed to statically forcing the webpage display to be a subclass of the scrollbar display. Thus, it is up to the scrollbar to decide whether it should display itself (instead of trying to force that responsibility on the webpage or on the external parts of the web browser). A webpage or web page is a page of the World Wide Web, usually in HTML/XHTML format (the file extensions are typically htm or html) and with hypertext links to enable navigation from one page or section to another. ... An example of a Web browser (Mozilla Firefox) A web browser is a software application that enables a user to display and interact with text, images, videos, music and other information typically located on a Web page at a website on the World Wide Web or a local area network. ...


Example

UML Diagram for the Window Example
UML Diagram for the Window Example

This Java example uses the window/scrolling scenario. Java language redirects here. ...

 // 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.


In C++ we have:

 #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 << 'n'; } }; /* 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" << 'n'; } }; /* ConcreteDecoratorB */ class ScrollDecorator : public Decorator { public: ScrollDecorator( Widget* w ) : Decorator( w ) { } void draw() { Decorator::draw(); cout << " ScrollDecorator" << 'n'; } }; int main( void ) { Widget* aWidget = new BorderDecorator( new ScrollDecorator( new TextField( 80, 24 ))); aWidget->draw(); delete aWidget; } 

In 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() + "nt" + "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("ttdoing DecorationA things"); } public override String getDescription() { return base.getDescription() + "nttincluding " + 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("ttdoing DecorationB things"); } public override String getDescription() { return base.getDescription() + "nttincluding " + 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("ttdoing DecorationC things"); } public override String getDescription() { return base.getDescription() + "nttincluding " + this.ToString(); } }// end class DecorationC : Decorator }// end of namespace GSL_Decorator_pattern 

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(decorator){ this.cost = function(){ return decorator.cost() + 0.5; }; } //Decorator B function Whip(decorator){ this.cost = function(){ return decorator.cost() + 0.7; }; } //Decorator C function Sprinkles(decorator){ this.cost = function(){ return decorator.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

This does not cite any references or sources. ... In computer programming, the adapter design pattern (often referred to as the wrapper pattern or simply a wrapper) adapts one interface for a class into one that a client expects. ... In object-oriented programming, a class consists of encapsulated instance variables and subprograms, the methods mentioned below. ... A software design pattern, the Abstract Factory Pattern provides a way to encapsulate a group of individual factories that have a common theme. ... In computer science, an immutable object, as opposed to a mutable object, is a kind of object whose internal states cannot be modified after it is created. ...

External links

In software engineering, a design pattern is a general reusable solution to a commonly occurring problem in software design. ... This article is about the book by Gamma et al. ... A software design pattern, the Abstract Factory Pattern provides a way to encapsulate a group of individual factories that have a common theme. ... The Builder Pattern is a software design pattern. ... The factory method pattern is an object-oriented design pattern. ... A prototype pattern is a creational design pattern used in software development when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects. ... In software engineering, the singleton pattern is a design pattern that is used to restrict instantiation of a class to one object. ... In computer programming, the adapter design pattern (often referred to as the wrapper pattern or simply a wrapper) adapts one interface for a class into one that a client expects. ... The bridge pattern is a design pattern used in software engineering which is meant to decouple an abstraction from its implementation so that the two can vary independently (Gamma et al. ... This does not cite any references or sources. ... Flyweight is a software design pattern. ... // In computer programming, the proxy pattern is a software design pattern. ... In Object Oriented Design, the chain-of-responsibility pattern is a design pattern consisting of a source of command objects and a series of processing objects. ... In object-oriented programming, the Command pattern is a design pattern in which objects are used to represent actions. ... In computer programming, the interpreter pattern is a particular design pattern. ... In object-oriented programming, an iterator is an object allowing one to sequence through all of the elements or parts contained in some other object, typically a container or list. ... The mediator pattern is a software design pattern that provides a unified interface to a set of interfaces in a subsystem. ... The memento pattern is a software design pattern that provides the ability to restore an object to its previous state (undo by rollback). ... The observer pattern (sometimes known as publish/subscribe) is a design pattern used in computer programming to observe the state of an object in a program. ... A behavioral software design pattern, state pattern is used in computer programming to represent the state of an object. ... In computer programming, the strategy pattern is a particular software design pattern, whereby algorithms can be selected on-the-fly at runtime. ... Template method: UML class diagram. ... In object-oriented programming and software engineering, the visitor design pattern is a way of separating an algorithm from an object structure. ...

  Results from FactBites:
 
three-ten software | innovation through education (243 words)
The object to be decorated is passed as an input parameter to construct a new decorated object.
The template method pattern is very similar to the strategy pattern in that it also allows events to occur in the middle of a call to a method, rather than before or after.
The filter pattern is a version of the decorator pattern which is used to manipulate data steams.
Design Pattern Synopses (4381 words)
The Filter pattern is a special case of the Decorator pattern, where a data source or data sink object is wrapped to add logic to the handling of a data stream.
The Composite pattern also allows the objects in the tree to be manipulated in a consistent manner, by requiring all of the objects in the tree to have a common superclass or interface.
The Flyweight pattern is often combined with the Composite pattern to represent the leaf nodes of a hierarchical structure with shared objects.
  More results at FactBites »


 
 

COMMENTARY     


Share your thoughts, questions and commentary here
Your name
Your comments

Want to know more?
Search encyclopedia, statistics and forums:

 


Lesson Plans | Student Area | Student FAQ | Reviews | Press Releases |  Feeds | Contact
The Wikipedia article included on this page is licensed under the GFDL.
Images may be subject to relevant owners' copyright.
All other elements are (c) copyright NationMaster.com 2003-5. All Rights Reserved.
Usage implies agreement with terms, 1022, m