Friday, December 7, 2007

Decorator Design Pattern

Decorator is always one of the most complicated Design Patterns.. until today. :) Nice and easy definition to remember.

The Decorator Pattern is used for adding additional functionality to a particular object as opposed to a class of objects. It is easy to add functionality to an entire class of objects by subclassing an object, but it is impossible to extend a single object this way. With the Decorator Pattern, you can add functionality to a single object and leave others like it unmodified.

A Decorator, also known as a Wrapper, is an object that has an interface identical to an object that it contains. Any calls that the decorator gets, it relays to the object that it contains, and adds its own functionality along the way, either before or after the call. This gives you a lot of flexibility, since you can change what the decorator does at runtime, as opposed to having the change be static and determined at compile time by subclassing. Since a Decorator complies with the interface that the object that it contains, the Decorator is indistinguishable from the object that it contains. That is, a Decorator is a concrete instance of the abstract class, and thus is indistinguishable from any other concrete instance, including other decorators. This can be used to great advantage, as you can recursively nest decorators without any other objects being able to tell the difference, allowing a near infinite amount of customization.

Decorators add the ability to dynamically alter the behavior of an object because a decorator can be added or removed from an object without the client realizing that anything changed. It is a good idea to use a Decorator in a situation where you want to change the behaviour of an object repeatedly (by adding and subtracting functionality) during runtime.

The dynamic behavior modification capability also means that decorators are useful for adapting objects to new situations without re-writing the original object's code.


More examples next time..

2 comments:

Binit pal singh said...

hi Sonu,
read about Decorator design pattern. Nicely written but you should also include some code examples; will be more helpfull to others.

thanks
a Guy from IT ( lifeissucking.blogspot.com )

Binit pal singh said...

hi Sonu,
read about Decorator design pattern. Nicely written but you should also include some code examples; will be more helpfull to others.

thanks
a Guy from IT ( lifeissucking.blogspot.com )