I have a story about the doctor who had a very good and fast car – Mercedes. On the way to work he is often stuck in traffic congestion and this makes him mad and late so as an impact his patients suffer. And he has a dream that his car became Ambulance and all cars make the way to him. Only one issue with this: Ambulance should beep and his car has no such ability so your task is to decorate Mersedes so when it goes it beeps.
How can you accomplish this?
So here we have Car class:
and the Mersedes implementation:
The Decorator pattern is used to add some functionality to your objects. In our example we want to add beeping to the concrete implementation of Car, but also we can add other functionality. So in order to save contract of Car class and have base class for all features we create the CarDecorator class like below:
as you see it has decoratedCar wrapped, that is why patterns is also called Wrapper.
So in order to add some additional functionality we derive from Decorator class:
so it was slight extension – beeping :)
And usage looks very friendly – we cover Mersedes with Ambulance features, after that we can cover it with more abilities, in other words we can add features dynamically.
I think you extected it. Now lets take a look at the UML diagram of this wisdom:
This pattern has some similarities to the Composite and Adapter patterns. Adapter could change the interface of behavior, but Decorator not (we are derived from Car). Composite works with lot of components, not like Decorator with only one.
What was interested for me here is usage of the IDEA instead of eclipse and I must say that this is just heaven to use it. I feel myself comfortable with Resharper so it was quite very easy to write code on the fly. And porting of code from eclipse did not make any issues…