I have a story about the doctor who had a very good and fast Mercedes. On the way to work he is often stuck in traffic congestion and this makes him mad and late making his patients suffer. He has a dream of his car becoming Ambulance so that all cars make the way. Only one issue with this: Ambulance should beep loud. Currently his car has no such loud horn. The doctor also doesn’t want to waive his warranty by changing internals of this car. Let’s decorate Mersedes so when you drive it beeps real loud. How can we accomplish this using a Decorator design pattern?

DECORATOR

So here we have Car class and Mersedes implementations:

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.

Output:

I’m Mercedes and I’m on my way…
…beep-beep-beep-…

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.