Computer Science Design Patterns/Decorator

{{Computer Science Design Patterns/Page The decorator pattern helps to add behavior or responsibilities to an object. This is also called “Wrapper”.
 * mode={{{mode|reading}}}
 * page={{{page|{{SUBPAGENAME}}}}}
 * stage=25
 * stage date=29 Jan, 2014
 * stage comment=Add more illustrations.
 * previous=Composite
 * next=Facade
 * content=

Cost
This pattern can be very expensive. You should only use it when it is really necessary. You should have lots of different behaviors and responsibilities for the same class.

Creation
This pattern is expensive to create.

Maintenance
This pattern can be expensive to maintain. If the representation of a class often changes, you will have lots of refactoring.

Removal
This pattern is hard to remove too.

Advises

 * Put the decorator term in the name of the decorator classes to indicate the use of the pattern to the other developers.

Implementations
This example illustrates a simple extension method for a bool type.

Coffee making scenario
The output of this program is given below:

The output of this program is given below:

First Example (window/scrolling scenario)
The following Java example illustrates the use of decorators using the window/scrolling scenario.

The following classes contain the decorators for all Window classes, including the decorator classes themselves. 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: 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 following classes contain the decorators for all Coffee classes, including the decorator classes themselves.. 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: The output of this program is given below:

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