Intent - Attach additional responsibilities to an
object dynamically. Decorators provide a flexible
alternative to subclassing for extending functionality.
Problem -
You want to add responsibilities to individual
objects dynamically and transparently without
affecting other objects
You want to create responsibilities that can be withdrawn
When you want to alter behavior of a set of classes
and extension by subclassing is
impractical. Sometimes a large number of independent
extensions are possible and would produce an explosion
of subclasses to support every combination. Or a class
definition may be hidden or otherwise unavailable for
subclassing.
Solution -
Participants and Collaborators
Component
ConcrecteComponent
Decorator
ConcreteDecorator
Consequences
More flexibility than static inheritance
Avoids feature-laden classes high up in the
hierarchy
A decorator and its component aren't identical
Lots of little objects - can be difficult to debug
Implementation
Interface conformance - the decorators need a common
interface
Omitting the abstract Decorator class - if adding
only a few Decorators
Keeping Component classes lightweight - the
subclasses should contain the guts, not the
superclass
Changing the skin of an object versus changing its
guts - this is a Decorator vs. Strategy issue.