Thursday 3 May 2007

Decorator Design Pattern

A decorator pattern allows additional responsibilities added to the object without subclassing. Subclassing means a class that inherits some properties from the superclass and decorator pattern is alternative to subclassing.[1]

Why is decorator design pattern alternative to subclassing or inheritance?
  1. Because subclassing adds behaviour during compilation and decorator pattern adds new responsibility or behaviour during run time.
  2. It's done without modifying the interface of the original object.
  3. Decorator pattern allows to add or remove functionality as and when required. [2]

Advantages of using Decorator Design Pattern over Subclassing are:

  1. Because adding functionalities are done during run time therefore it gives more flexibility than just straight inheritance.
  2. It saves time and simplifies coding because you need not write coding from the start and just code the behaviour into the object.
  3. Unnessary functionalites need not be added. It can be done upon request.
  4. In any case when you do not have access to the source code but you need to add the functionalities to the product, then you can wrap this object into the decorator object to provide the missing or new functionalities.[3]

---------------------------------------------------------------------------------------------------

REFERENCE

[1], [2] & [3] http://en.wikipedia.org/wiki/Decorator_pattern

3 comments:

MUINDE LILIAN - PAFSD said...

Hi
very well explained pattern, I found the advantages very useful.
cheers
Lilian

Rizwan Khan said...

Hi
That right, decorator also makes adding future options/functionalities easier as you've mentioned in bullet no 3 but for each new functionality, would there be another Decorator ( e.g frame, Taxcalc, fileRead etc.) or all can be under one decorator? I think its good practice to make them seperate but then there will be lots of classes and complications.
Whats a better way of using multiple decorators? I am looking for that answer, any idea?
Regards

Imtiaz said...

hey

well explained and cool reasoning. but to be honest i dont really like the idea of decorator patterns as you need to rely on only one class. Because of too much editing in terms of code such as methods and functions it might turn into GOD class, which may easily lead the developer in to creating mess such as anti pattern. conversly, inheritance is a key concept in OOP so we should appreciate the art of using inheritance and subclassing. what do you think?