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?

DECORATOR

So here we have Car class:

public
class Car {
    protected String BrandName;

    public void Go(){
        System.out.println(“I’m “+BrandName+” and I’m on my way…”);
    }
}

and the Mersedes implementation:

public
class
MercedesCar extends
Car {
    public
MercedesCar() {
        BrandName = “Mercedes”;
    }
}

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:

public
class
CarDecorator extends
Car{
    protected
Car decoratedCar;

    public
CarDecorator(Car car) {
        decoratedCar = car;
    }

    @Override
    public void Go() {
        decoratedCar.Go();
    }
}

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:

public
class
AmbulanceCar extends
CarDecorator {
    public
AmbulanceCar(Car car) {
        super(car);
    }

    @Override
    public void Go() {
        super.Go();
        System.out.println(“…beep-beep-beep-…”);
    }
}

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.

        Car doctorsDream = new
AmbulanceCar(new MercedesCar());
        doctorsDream.Go();

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.

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…

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInEmail this to someone