Tuesday, July 31, 2012

Decorator Pattern

Decorator Pattern adds additional attributes to an object dynamically.

Picture frame would be a example. The picture is an object which has own attributes. But for the display purposes we add a frame, in order to decorate it.

In programming world, Decorator pattern is about the wrapper objects. The definition is, "Allows for the dynamic wrapping of objects in order to modify their existing responsibilities and behaviors"

We'll create an ice cream application, Vanilla/chocolate ice cream will be decorated with almonds/honey.

Create an interface which contains the MakeIceCream functionality.
Using above interface create vanilla and chocolate ice cream create implementation.
We need to decorate that vanilla/chocolate ice cream. This should happen without effecting the existing class structure.
For that, create a decorator class by implementing the IceCream interface.
Using the above decorator class we can create Honey/Almond decorated ice cream like below.
 Now we can create a program to demonstrate how the decorators will be used.