The Decorator Pattern
Decorators are a structural design pattern that aim to promote code reuse. Similar to Mixins, they can be considered another viable alternative to object subclassing.
Classically, Decorators offered the ability to add behavior to existing classes in a system dynamically. The idea was that the decoration itself wasn’t essential to the base functionality of the class; otherwise, it would be baked into the superclass itself.
They can be used to modify existing systems where we wish to add additional features to objects without the need to heavily modify the underlying code using them. A common reason why developers use them is that their applications may contain features requiring a large quantity of distinct types of object. Imagine having to define hundreds of different object constructors for, say, a JavaScript game (Figure 9-11).

Figure 9-11. Decorator pattern
The object constructors could represent distinct player types, each
with differing capabilities. A Lord of the Rings game
could require constructors for Hobbit,
Elf, Orc, Wizard,
Mountain Giant, Stone Giant, and so on, but there could easily
be hundreds of these. If we then factored in capabilities, imagine having
to create subclasses for each
combination of capability type—e.g., HobbitWithRing, HobbitWithSword, HobbitWithRingAndSword, and so on. This isn’t very practical and certainly isn’t manageable when ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access