Why is decorator design pattern alternative to subclassing or inheritance?
- Because subclassing adds behaviour during compilation and decorator pattern adds new responsibility or behaviour during run time.
- It's done without modifying the interface of the original object.
- Decorator pattern allows to add or remove functionality as and when required. [2]
Advantages of using Decorator Design Pattern over Subclassing are:
- Because adding functionalities are done during run time therefore it gives more flexibility than just straight inheritance.
- It saves time and simplifies coding because you need not write coding from the start and just code the behaviour into the object.
- Unnessary functionalites need not be added. It can be done upon request.
- 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