Decorator-pattern: Let´s wrap the world in classes.

Chances and risks of the decorator-pattern

The decorator-pattern

The decorator design-pattern was first defined in the eponymous book by the gang of four. In short, a class is used to wrap another class with the same interface.
A simple skeleton in Java would look like:
class A implements Interface {
}

class B implements Interface {
    private A a;
	B(A a) {
        this.a = a;
	}
}
				

The purpose

With this method, the functionality of the original class can be altered. For example it is possible to do a parameter verification on an unverified object. It is also possible to build a chain of objects, even with the same type. That could be interesting if you need to calculate the price of a product and can alter it like with an extra-charge for a different color. In that case the outer class calculates the price by adding its price to the inner one.

The limitations

It would also be possible to extend an original class by new functions. Though in that case the new class could be used instead of the original one, but it cannot offer its new functionality because of the limitation to the Interface.
Another withdraw could be that there is no possibility to access the wrapped classes directly. If the common interface does not support a function of the wrapped class, you cannot access it anymore.
More uncomfortable is the fact, that a wrapped class that implements more than one interface would also cause the decorator to implement multiple interfaces. So that would end up in a combination of responsibilities.

Conclusion

Though a decorator can offer some nice features to extend or protect existing classes, it can also be the main withdraw, because you possibly cannot access functions of the wrapped class directly anymore.