1.3.1. Decorator Intent

From the book:

Intent: “Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.” (GoF 1994, p. 175)

When we want to add new methods to a class, the easiest approach is to add them to a subclass. However, this may lead to clumsy class hierarchies, and risks duplication of code due to the inability to extend more than one superclass. A better approach is the decorator pattern, with which we decorate an object with a richer class and thereby “attach additional responsibilities”. We can also use this pattern to remove methods that we do not want to support. This is called “filtering”.

In the GoF book, both adapter and decorator are called a “wrapper”. Be careful with naming. A weak name like “wrapper” is bound to cause confusion.

Discussion

0 comments