Decorator pattern
   HOME

TheInfoList



OR:

In
object-oriented programming Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which can contain data and code. The data is in the form of fields (often known as attributes or ''properties''), and the code is in the form of ...
, the decorator pattern is a design pattern that allows behavior to be added to an individual
object Object may refer to: General meanings * Object (philosophy), a thing, being, or concept ** Object (abstract), an object which does not exist at any particular time or place ** Physical object, an identifiable collection of matter * Goal, an ...
, dynamically, without affecting the behavior of other objects from the same
class Class or The Class may refer to: Common uses not otherwise categorized * Class (biology), a taxonomic rank * Class (knowledge representation), a collection of individuals or objects * Class (philosophy), an analytical concept used differently ...
. The decorator pattern is often useful for adhering to the
Single Responsibility Principle The single-responsibility principle (SRP) is a computer programming principle that states that "A module should be responsible to one, and only one, actor." The term actor refers to a group (consisting of one or more stakeholders or users) that ...
, as it allows functionality to be divided between classes with unique areas of concern as well as to the Open-Closed Principle, by allowing the functionality of a class to be extended without being modified. Decorator use can be more efficient than subclassing, because an object's behavior can be augmented without defining an entirely new object.


Overview

The ''decorator'' design pattern is one of the twenty-three well-known ''
design patterns ''Design Patterns: Elements of Reusable Object-Oriented Software'' (1994) is a software engineering book describing software design patterns. The book was written by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides, with a forewo ...
''; these describe how to solve recurring design problems and design flexible and reusable object-oriented software—that is, objects which are easier to implement, change, test, and reuse.


What problems can it solve?

* Responsibilities should be added to (and removed from) an object dynamically at run-time. * A flexible alternative to subclassing for extending functionality should be provided. When using subclassing, different subclasses extend a class in different ways. But an extension is bound to the class at compile-time and can't be changed at run-time.


What solution does it describe?

Define Decorator objects that * implement the interface of the extended (decorated) object (Component) transparently by forwarding all requests to it * perform additional functionality before/after forwarding a request. This allows working with different Decorator objects to extend the functionality of an object dynamically at run-time.
See also the UML class and sequence diagram below.


Intent

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 Class or The Class may refer to: Common uses not otherwise categorized * Class (biology), a taxonomic rank * Class (knowledge representation), a collection of individuals or objects * Class (philosophy), an analytical concept used differently ...
, 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; # In the ''Decorator'' class, pass a ''Component'' to the ''Decorator'' constructor to initialize the ''Component'' pointer; # In the ''Decorator'' class, forward 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 previous 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 previous example, 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 In computer science, compile time (or compile-time) describes the time window during which a computer program is compiled. The term is used as an adjective to describe concepts related to the context of program compilation, as opposed to concep ...
, and the change affects all instances of the original class; decorating can provide new behavior at run-time for selected 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 Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's mo ...
and the
.NET Framework The .NET Framework (pronounced as "''dot net"'') is a proprietary software framework developed by Microsoft that runs primarily on Microsoft Windows. It was the predominant implementation of the Common Language Infrastructure (CLI) until bein ...
incorporate the decorator pattern.


Motivation

As an example, consider a window in a
windowing system In computing, a windowing system (or window system) is software that manages separately different parts of display screens. It is a type of graphical user interface (GUI) which implements the WIMP ( windows, icons, menus, pointer) paradigm f ...
. To allow
scrolling In computer displays, filmmaking, television production, and other kinetic displays, scrolling is sliding text, images or video across a monitor or display, vertically or horizontally. "Scrolling," as such, does not change the layout of the text ...
of the window's contents, one may wish to add horizontal or vertical
scrollbar A scrollbar is an interaction technique or widget (GUI), widget in which continuous text, pictures, or any other content can be Scrolling, scrolled in a predetermined direction (up, down, left, or right) on a computer display, window (computing), ...
s to it, as appropriate. Assume windows are represented by instances of the ''Window'' interface, 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, a new ''BorderedWindowDecorator'' is created. Any combination of ''ScrollingWindowDecorator'' or ''BorderedWindowDecorator'' can decorate existing windows. If the functionality needs to be added to all Windows, the base class can be modified. On the other hand, sometimes (e.g., using external frameworks) it is not possible, legal, or convenient to modify the base class. In the previous example, 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.


Common usecases


Applying decorators

Adding or removing decorators on command (like a button press) is a common UI pattern, often implemented along with the Command design pattern. For example, a text editing application might have a button to highlight text. 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). Applying or removing decorators based on changes in state is another common use case. Depending on the scope of the state, decorators can be applied or removed in bulk. Similarly, the State design pattern can be implemented using decorators instead of subclassed objects encapsulating the changing functionality. The use of decorators in this manner makes the State object's internal state and functionality more compositional and capable of handling arbitrary complexity.


Usage in Flyweight objects

Decoration is also often used in the Flyweight design pattern. Flyweight objects are divided into two components: an invariant component that is shared between all flyweight objects; and a variant, decorated component that may be partially shared or completely unshared. This partitioning of the flyweight object is intended to reduce memory consumption. The decorators are typically cached and reused as well. The decorators will all contain a common reference to the shared, invariant object. If the decorated state is only partially variant, than the decorators can also be shared to some degree - though care must be taken not to alter their state while they're being used. iOS's UITableView implements the flyweight pattern in this manner - a tableview's reusable cells are decorators that contains a references to a common tableview row object, and the cells are cached / reused.


Obstacles of interfacing with decorators

Applying combinations of decorators in diverse ways to a collection of objects introduces some problems interfacing with the collection in a way that takes full advantage of the functionality added by the decorators. The use of an Adapter or
Visitor A visitor, in English and Welsh law and history, is an overseer of an autonomous ecclesiastical or eleemosynary institution, often a charitable institution set up for the perpetual distribution of the founder's alms and bounty, who can inter ...
patterns can be useful in such cases. Interfacing with multiple layers of decorators poses additional challenges and logic of Adapters and Visitors must be designed to account for that.


Architectural relevance

Decorators support a compositional rather a top-down, hierarchical approach to extending functionality. A decorator makes it possible to add or alter behavior of an interface at run-time. They can be used to wrap objects in a multilayered, arbitrary combination of ways. Doing the same with subclasses means implementing complex networks of multiple inheritance, which is memory-inefficient and at a certain point just cannot scale. Likewise, attempting to implement the same functionality with properties bloats each instance of the object with unnecessary properties. For the above reasons decorators are often considered a memory-efficient alternative to subclassing. Decorators can also be used to specialize objects which are not subclassable, whose characteristics need to be altered at runtime (as mentioned elsewhere), or generally objects that are lacking in some needed functionality.


Usage in enhancing APIs

The decorator pattern also can augment the Facade pattern. A facade is designed to simply interface with the complex system it encapsulates, but it does not add functionality to the system. However, the wrapping of a complex system provides a space that may be used to introduce new functionality based on the coordination of subcomponents in the system. For example, a facade pattern may unify many different languages dictionaries under one multi-language dictionary interface. The new interface may also provide new functions for translating words between languages. This is a hybrid pattern - the unified interface provides a space for augmentation. Think of decorators as not being limited to wrapping individual objects, but capable of wrapping clusters of objects in this hybrid approach as well.


Alternatives to Decorators

As an alternative to the decorator pattern, the adapter can be used when the wrapper must respect a particular interface and must support polymorphic behavior, and the Facade when an easier or simpler interface to an underlying object is desired.


Structure


UML class and sequence diagram

In the above UML
class diagram In software engineering, a class diagram in the Unified Modeling Language (UML) is a type of static structure diagram that describes the structure of a system by showing the system's classes, their attributes, operations (or methods), and the rela ...
, the abstract Decorator class maintains a reference (component) to the decorated object (Component) and forwards all requests to it (component.operation()). This makes Decorator transparent (invisible) to clients of Component. Subclasses (Decorator1,Decorator2) implement additional behavior (addBehavior()) that should be added to the Component (before/after forwarding a request to it).
The sequence diagram shows the run-time interactions: The Client object works through Decorator1 and Decorator2 objects to extend the functionality of a Component1 object.
The Client calls operation() on Decorator1, which forwards the request to Decorator2. Decorator2 performs addBehavior() after forwarding the request to Component1 and returns to Decorator1, which performs addBehavior() and returns to the Client.


Examples


Go

package decolog import ( "log" "time" ) //OperateFn represents operations that require decoration type OperateFn func() //Decorate the operation func Decorate(opFn OperateFn) // package main package main import ( "github.com/tkstorm/go-design/structural/decorator/decolog" "log" "math/rand" "time" ) //output: //2019/08/19 19:05:24 finish action a //2019/08/19 19:05:24 elapsed time 77 ms //2019/08/19 19:05:24 finish action b //2019/08/19 19:05:24 elapsed time 88 ms func main() func DoActionA() func DoActionB()


C++

Two options are presented here: first, a dynamic, runtime-composable decorator (has issues with calling decorated functions unless proxied explicitly) and a decorator that uses mixin inheritance.


Dynamic Decorator

#include #include struct Shape ; struct Circle : Shape ; struct ColoredShape : Shape ; int main() #include #include #include struct WebPage ; struct BasicWebPage : WebPage ; struct WebPageDecorator : WebPage ; struct AuthenticatedWebPage : WebPageDecorator ; struct AuthorizedWebPage : WebPageDecorator ; int main(int argc, char* argv[])


Static Decorator (Mixin Inheritance)

This example demonstrates a static Decorator implementation, which is possible due to C++ ability to inherit from the template argument. #include #include struct Circle ; template struct ColoredShape : public T ; int main()


Java


First example (window/scrolling scenario)

The following Java example illustrates the use of decorators using the window/scrolling scenario. // The Window interface class public interface Window // Implementation of a simple Window without any scrollbars class SimpleWindow implements 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 // The first concrete decorator which adds vertical scrollbar functionality class VerticalScrollBarDecorator extends WindowDecorator // The second concrete decorator which adds horizontal scrollbar functionality class HorizontalScrollBarDecorator extends WindowDecorator 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 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. Below is the JUnit test class for the Test Driven Development import static org.junit.Assert.assertEquals; import org.junit.Test; public class WindowDecoratorTest


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 interface Coffee defines the functionality of Coffee implemented by decorator public interface Coffee // Extension of a simple coffee without any extra ingredients public class SimpleCoffee implements Coffee The following classes contain the decorators for all classes, including the decorator classes themselves. // Abstract decorator class - note that it implements Coffee interface public abstract class CoffeeDecorator implements Coffee // Decorator WithMilk mixes milk into coffee. // Note it extends CoffeeDecorator. class WithMilk extends CoffeeDecorator // Decorator WithSprinkles mixes sprinkles onto coffee. // Note it extends CoffeeDecorator. class WithSprinkles extends CoffeeDecorator Here's a test program that creates a instance which is fully decorated (with milk and sprinkles), and calculate cost of coffee and prints its ingredients: public class Main The output of this program is given below:
Cost: 1.0; Ingredients: Coffee
Cost: 1.5; Ingredients: Coffee, Milk
Cost: 1.7; Ingredients: Coffee, Milk, Sprinkles


PHP

abstract class Component class ConcreteComponent extends Component abstract class Decorator extends Component class ConcreteDecorator1 extends Decorator class ConcreteDecorator2 extends Decorator class Client $client = new Client(); // Result: #quanton81 //Concrete Component: 1000 //Concrete Decorator 1: 500 //Concrete Decorator 2: 500 //Client: 2000


Python

The following Python example, taken fro
Python Wiki - DecoratorPattern
shows us how to pipeline decorators to dynamically add many behaviors in an object: """ Demonstrated decorators in a world of a 10x10 grid of values 0-255. """ import random def s32_to_u16(x): if x < 0: sign = 0xF000 else: sign = 0 bottom = x & 0x00007FFF return bottom , sign def seed_from_xy(x, y): return s32_to_u16(x) , (s32_to_u16(y) << 16) class RandomSquare: def __init__(s, seed_modifier): s.seed_modifier = seed_modifier def get(s, x, y): seed = seed_from_xy(x, y) ^ s.seed_modifier random.seed(seed) return random.randint(0, 255) class DataSquare: def __init__(s, initial_value=None): s.data = nitial_value* 10 * 10 def get(s, x, y): return s.data y * 10) + x # yes: these are all 10x10 def set(s, x, y, u): s.data y * 10) + x= u class CacheDecorator: def __init__(s, decorated): s.decorated = decorated s.cache = DataSquare() def get(s, x, y): if s.cache.get(x, y)

None: s.cache.set(x, y, s.decorated.get(x, y)) return s.cache.get(x, y) class MaxDecorator: def __init__(s, decorated, max): s.decorated = decorated s.max = max def get(s, x, y): if s.decorated.get(x, y) > s.max: return s.max return s.decorated.get(x, y) class MinDecorator: def __init__(s, decorated, min): s.decorated = decorated s.min = min def get(s, x, y): if s.decorated.get(x, y) < s.min: return s.min return s.decorated.get(x, y) class VisibilityDecorator: def __init__(s, decorated): s.decorated = decorated def get(s, x, y): return s.decorated.get(x, y) def draw(s): for y in range(10): for x in range(10): print "%3d" % s.get(x, y), print # Now, build up a pipeline of decorators: random_square = RandomSquare(635) random_cache = CacheDecorator(random_square) max_filtered = MaxDecorator(random_cache, 200) min_filtered = MinDecorator(max_filtered, 100) final = VisibilityDecorator(min_filtered) final.draw()
Note: Please do not confuse the Decorator Pattern (or an implementation of this design pattern in Python - as the above example) with Python Decorators, a Python language feature. They are different things. Second to the Python Wiki:
The Decorator Pattern is a pattern described in the Design Patterns Book. It is a way of apparently modifying an object's behavior, by enclosing it inside a decorating object with a similar interface. This is not to be confused with Python Decorators, which is a language feature for dynamically modifying a function or class.


Crystal

abstract class Coffee abstract def cost abstract def ingredients end # Extension of a simple coffee class SimpleCoffee < Coffee def cost 1.0 end def ingredients "Coffee" end end # Abstract decorator class CoffeeDecorator < Coffee protected getter decorated_coffee : Coffee def initialize(@decorated_coffee) end def cost decorated_coffee.cost end def ingredients decorated_coffee.ingredients end end class WithMilk < CoffeeDecorator def cost super + 0.5 end def ingredients super + ", Milk" end end class WithSprinkles < CoffeeDecorator def cost super + 0.2 end def ingredients super + ", Sprinkles" end end class Program def print(coffee : Coffee) puts "Cost: #; Ingredients: #" end def initialize coffee = SimpleCoffee.new print(coffee) coffee = WithMilk.new(coffee) print(coffee) coffee = WithSprinkles.new(coffee) print(coffee) end end Program.new Output:
Cost: 1.0; Ingredients: Coffee
Cost: 1.5; Ingredients: Coffee, Milk
Cost: 1.7; Ingredients: Coffee, Milk, Sprinkles


C#

namespace WikiDesignPatterns; public interface IBike public class AluminiumBike : IBike public class CarbonBike : IBike public abstract class BikeAccessories : IBike public class SecurityPackage : BikeAccessories public class SportPackage : BikeAccessories public class BikeShop Output:
Bike: 'Aluminium Bike + Sport Package + Security Package' Cost: 111


See also

* Composite pattern * Adapter pattern *
Abstract class In programming languages, an abstract type is a type in a nominative type system that cannot be instantiated directly; a type that is not abstract – which ''can'' be instantiated – is called a ''concrete type''. Every instance of an abstra ...
*
Abstract factory The abstract factory pattern provides a way to encapsulate a group of individual factories that have a common theme without specifying their concrete classes. In normal usage, the client software creates a concrete implementation of the abstract fa ...
* Aspect-oriented programming *
Immutable object In object-oriented and functional programming, an immutable object (unchangeable object) is an object whose state cannot be modified after it is created.Goetz et al. ''Java Concurrency in Practice''. Addison Wesley Professional, 2006, Section 3. ...


References


External links


Decorator Pattern
implementation in Java * Decorator pattern description from the Portland Pattern Repository {{DEFAULTSORT:Decorator Pattern Software design patterns Articles with example Java code