Definition
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.
Explanation
The decorator pattern can be used to extend (decorate) the functionality of a certain object statically, or in some cases at run-time, 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).
Note that decorators and the original class object share a common set of features. In the UML diagram, the “operation()” method was available in both
the decorated and undecorated versions.
The decoration features (e.g., methods, properties, or other members) are usually defined by an interface, mixin (a.k.a. “trait”) or class inheritance which is shared by the decorators and the decorated object. In the UML diagram the class “Component” is inherited by both the “ConcreteComponent” and the subclasses that descend from “Decorator”.
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 run-time 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.
As an example, consider a window in a windowing system. To allow scrolling of the window’s contents, one 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. One could create a subclass ScrollingWindow that provides them, or create a ScrollingWindowDecorator that adds this functionality to existing Window objects. At this point, either solution would be fine.
Now, assume one also desires the ability to add borders to windows. Again, the original Window class has no support. The ScrollingWindow subclass now poses a problem, because it has effectively created a new kind of window. If one wishes to add border support to many but not all windows, one must create subclasses WindowWithBorder and ScrollingWindowWithBorder etc. This problem gets worse with every new feature or window subtype 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. Notice that if the functionality needs to be added to all Windows, you could modify the base class and that will do. On the other hand, sometimes (e.g., using external frameworks) it is not possible, legal, or convenient to modify the base class.
Note, in the previous example, that the “SimpleWindow” and “WindowDecorator” classes implement the “Window” interface, which defines the “draw()” method and the “getDescription()” method, that are required in this scenario, in order to decorate a window control.
Screencast
TypeScript Code
module ThirdpartyLib { export interface ILibraryItem { copies: number; display(): void; } export class LibraryItem implements ILibraryItem { private _copies: number; public get copies(): number { return this._copies; } public set copies(value: number) { this._copies = value; } public display(): void { throw new Error("Method not implemented"); } } export class Book extends LibraryItem { constructor(private author: string, private title: string, copies: number) { super(); this.copies = copies; } public display(): void { Output.WriteLine("Book:"); Output.WriteLine("--Author: " + this.author); Output.WriteLine("--Title: " + this.title); Output.WriteLine("--# Copies: " + this.copies); Output.WriteLine(""); } } export class Video extends LibraryItem { constructor(private director: string, private title: string, private playTime: number, copies: number) { super(); this.copies = copies; } public display(): void { Output.WriteLine("Video:"); Output.WriteLine("--Director: " + this.director); Output.WriteLine("--Title: " + this.title); Output.WriteLine("--Play Time: " + this.playTime); Output.WriteLine("--# Copies: " + this.copies); Output.WriteLine(""); } } } module Decorator { class Decorator implements ThirdpartyLib.ILibraryItem { private _libraryItem: T; constructor(libraryItem: T) { this._libraryItem = libraryItem; } public get libraryItem(): T { return this._libraryItem; } public get copies(): number { return this._libraryItem.copies; } public set copies(value: number) { this._libraryItem.copies = value; } public display(): void { this._libraryItem.display(); } } class Borrowable extends Decorator { private borrowers: Array = new Array(); constructor(libraryItem: T) { super(libraryItem); } public borrowItem(name: string): void { this.borrowers.push(name); this.libraryItem.copies--; } public returnItem(name: string): void { this.borrowers.splice(this.borrowers.indexOf(name)); this.libraryItem.copies++; } public display(): void { super.display(); Output.WriteLine("--borrowers:"); this.borrowers.forEach((borrower) => { Output.WriteLine("----borrower: " + borrower); }); Output.WriteLine("------"); } } window.addEventListener("load", function () { var book = new ThirdpartyLib.Book("Worley", "Inside ASP.NET", 10); book.display(); var borrowableBook = new Borrowable(book); borrowableBook.borrowItem("Book borrower #1"); borrowableBook.borrowItem("Book borrower #2"); borrowableBook.display(); var video = new ThirdpartyLib.Video("Spielberg", "Jaws", 23, 92); video.display(); var borrowableVideo = new Borrowable(video); borrowableVideo.borrowItem("Video borrower #1"); borrowableVideo.borrowItem("Video borrower #2"); borrowableVideo.display(); }); }
Output