|

The decorator pattern is a structural pattern that adds responsibilities to objects dynamically at runtime, without affecting the object.

The object to be decorated is passed as an input parameter to construct a new decorated object.

The decorator pattern provides an efficient alternative to inheritance. By using the decorator pattern, one can avoid implementation of multiple sub-classes with similar functionalities. Also, responsibilities can be added to individual objects, not the whole class. The decorator pattern provides more flexibility than sub-classing and since functionality is added to objects as it is needed, the decorator pattern allows us to be more resource efficient.

It creates many small objects when objects are being decorated.

There are four patterns that are related to the decorator pattern. These are the delegation pattern, the filter pattern, the strategy pattern, and the template method pattern.
- The delegation pattern is very similar to the decorator pattern in that the decorator pattern is just a structured way of implementing the delegation pattern.
- The strategy pattern allows events to happen in the middle of calls to a method, whereas the decorator pattern allows events to happen before or after calls to a method.
- The template method pattern is very similar to the strategy pattern in that it also allows events to occur in the middle of a call to a method, rather than before or after.
- The filter pattern is a version of the decorator pattern which is used to manipulate data steams.
|