7/30/2011

Design Pattern - Decorator

Definition
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.(extend method, behavior of class)

UML Class Diagram

Decorator: when and where use it
- The intent of the Decorator design pattern is to let you extend an object?s behavior dynamically. This ability to dynamically attach new behavior to objects is done by a Decorator class that „wraps itself? around the original class.

- The Decorator pattern combines polymorphism with delegation. It is polymorphic with the original class so that clients can invoke it just like the original class. In most cases, method calls are delegated to the original class and then the results are acted upon, or decorated, with additional functionality. Decoration is a flexible technique because it takes place at runtime, as opposed to inheritance which take place at compile time. 
Sample
- Component abstract class

- Component concrete class

- Decorate abstract class

- Decorate concrete class

- Main class


Ref: Gang of Four tutorial

No comments:

Post a Comment