Decorator

From CSSEMediaWiki
(Difference between revisions)
Jump to: navigation, search
m
Line 33: Line 33:
 
* Inheritance hierarchy that has a Component interface.
 
* Inheritance hierarchy that has a Component interface.
 
* Decorator class has protected/private Component field that holds one Component instance.
 
* Decorator class has protected/private Component field that holds one Component instance.
 
  
 
==See also==
 
==See also==
 +
*[[Composite]]
 
*[[Strategy]]
 
*[[Strategy]]

Revision as of 00:54, 8 October 2008

The Decorator pattern makes it possible to add new/additional behavior/functionality to an existing class dynamically. This works by adding a decorator class, which has the same interface as the original (decorated) class. The decorator class wraps the original class which is usually achieved by passing the original object as a parameter to the constructor of the decorator when it is created.

The decorator pattern is an alternative to subclassing (see Strategy). While subclasssing adds behaviour at compile time, the decorator pattern can provide new funtionality at runtime.

Contents

Typical Usage

  • to add functionality to individual objects dynamically and transparently, that is, without affecting other objects.
  • for behaviour that can be withdrawn.
  • when extension by subclassing is impractical. Sometimes a large number of independent extensions are possible and would produce an explosion of subclasses to support every combination. Or a class definition may be hidden or otherwise unavailable for subclassing.

Example

A nice example is a webbrowser. A webbrowser is viewing webpages. The webpage itself displays the information and the webbrowser knows nothing about the content of the webpage. So it is possible that the webpage doesn't fit into the webbrowsers window. Therefore windowscrollbars are needed to show the information. However the browser shouldn't assume that scrollbars are always required and certainly it should never assume scrollbars are not needed at all. So scrollbars are just displayed when really required. Thus in this case the decorator adds dynamically scrollbars to the window of the webpage whenever they are needed.

UML-Diagram

Decorator.jpeg

Participating Classes

Component

Defines the abstract interface of the decorated object which can have added funtionality dynamically.

ConcreteComponent

Defines an object to which additional behaviour can be attached.

Decorator

Maintains a reference to the Component and defines a interface which complies to the Components interface.

ConcreteDecorator

Adds new functionality to the Component

Recognising the pattern

Classes: Component, ConcreteComponene, Decorator, ConcreteDecorator

  • Inheritance hierarchy that has a Component interface.
  • Decorator class has protected/private Component field that holds one Component instance.

See also

Personal tools