Decorator Pattern is a structural pattern that allows for the dynamic wrapping of objects in order to modify their existing responsibilities and behaviors and leads to the Open Close Principle (Closed for Modification, Open for Extension) One of the most important software principles of the development process that developers have to consider in change, the Decorator pattern helps us to design code avoiding modification, while still extending that code if needed.
We want to add behavior or state to individual objects at run-time. Inheritance is not feasible because it is static and applies to an entire class at the compile time.
We solved this using the decorator pattern by designing a new decorator class that wraps the original class. This wrapping could be achieved by the following sequence of steps:
- Create Subclass from the original "Component" class called "Decorator" Class.
- In this subclass - "Decorator" Class - add a Component pointer as a field.
- Pass a Component to the Decorator constructor to initialize the Component field pointer.
- In the Decorator Class, redirect all "Component" methods to the "Component" field pointer.
- In the ConcreteDecorator Class, override any Component method(s) whose behavior needs to be modified.
Finally, when we want to add some functionality to individual object or change the state of particular object at run time it is not possible; however, we can provide the specific behavior to all the objects of that class at design time by the help of inheritance or using subclass, but Decorator pattern makes it possible to provide individual object of same class a specific behavior or state at run time. This doesn’t affect other object of same Class.
Reference : http://en.wikipedia.org/wiki/Decorator_pattern