Notes on the Decorator Design Pattern
The Decorator Pattern (a.k.a. wrapper) belongs to the catalogue of structural patterns as defined in the book Design Patterns by GoF.
This pattern intends to dynamically and transparently attach additional responsibility to an object instead of using inheritance. It is recognizable by creational methods taking an instance of the same abstract/interface type which adds additional behaviour. (One example can be found here.)
Two key features of this pattern are that:
- The decorator (wrapper) conforms to the same interface of the object that is being decorated (wrappee).
- Decorators can be nested.
This article explains the Decorator Pattern in more detail with examples. It also discusses the pros and cons of this pattern to facilitate its proper usage.
The Decorator Pattern and some programming languages
Python
This page shows an example of the Decorator Pattern in Python. In Python, there is also a language feature called Decorator, but it is different from the Decorator Pattern because it is for modifying a function or class.
Kotlin
The Kotlin programming language has a feature extension that can add new functionalities to a class without using inheritance or the Decorator Pattern.
Java
Examples of the Decorator Pattern can be found in the source code of Java core libraries, such as what is described here. This is also a good example showing the two features of this pattern mentioned above.