Thursday, October 16, 2008

Design Patterns (3) - Decorator

Decorator: Attach additional responsibilities to an object dynamically keeping the same interface. Decorators provide a flexible alternative to subclassing for extending functionality.

image

The idea:

  • Start with a basic component and "decorate" it with condiments at runtime.
  • Decorators have the same supertype as the objects they decorate.
  • Given that the decorator has the same supertype as the object it decorates, we can pass around a decorated object in place of the original object.
  • The decorator adds its own behavior either before and/or after delegating to the object it decorates to do the rest of the job.
  • Objects can be decorated at any time, so we can decorate objects dynamically at runtime with as many decorators as we like.

 

 

image