[1] The decorator pattern is often useful for adhering to the Single Responsibility Principle, as it allows functionality to be divided between classes with unique areas of concern[2] as well as to the Open-Closed Principle, by allowing the functionality of a class to be extended without being modified.
The decorator pattern provides a flexible alternative to subclassing for extending functionality.
However, an extension is bound to the class at compile-time and can't be changed at run-time.
The decorator pattern allows responsibilities to be added (and removed from) an object dynamcally at run-time.
This wrapping could be achieved by the following sequence of steps: 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.
The decoration features (e.g., methods, properties, or other members) are usually defined by an interface, mixin (a.k.a.
In the previous example, the class Component is inherited by both the ConcreteComponent and the subclasses that descend from Decorator.
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.
By contrast, decorators are objects, created at runtime, and can be combined on a per-use basis.
To allow scrolling of the window's contents, one may wish to add horizontal or vertical scrollbars to it, as appropriate.
If one wishes to add border support to many but not all windows, one must create subclasses WindowWithBorder and ScrollingWindowWithBorder, etc.
On button press, the individual text glyphs currently selected will all be wrapped in decorators that modify their draw() function, causing them to be drawn in a highlighted manner (a real implementation would probably also use a demarcation system to maximize efficiency).
Similarly, the State design pattern can be implemented using decorators instead of subclassed objects encapsulating the changing functionality.
Interfacing with multiple layers of decorators poses additional challenges and logic of Adapters and Visitors must be designed to account for that.
Doing the same with subclasses means implementing complex networks of multiple inheritance, which is memory-inefficient and at a certain point just cannot scale.
Subclasses (Decorator1,Decorator2) implement additional behavior (addBehavior()) that should be added to the Component (before/after forwarding a request to it).
This example demonstrates a static Decorator implementation, which is possible due to C++ ability to inherit from the template argument.
This is not to be confused with Python Decorators, which is a language feature for dynamically modifying a function or class.