Friday, January 21, 2011

Decorator Pattern

The Decorator Pattern attaches additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.
Subclassing components would extend functionality at compile time. Fortunately, however, the Decorator Pattern does this at run time. The pattern means that classes are open for extension but closed for modification.

This pattern wraps a concrete component with one or more decorations, or additional responsibilities. Decorations are derived from an abstract decorator class which in turn inherits from an abstract component superclass.

The concrete decorator class is passed a component in its constructor, so that operations inherited from the abstract component superclass can build on - decorate - the component.

An implementation of the Decorator Pattern carries with it an assumption that the abstract component superclass type is satisfactory to the rest of your code. You should consider another pattern if the concrete component type is what the rest of your code depends on.

No comments:

Post a Comment