decoration via constructor injection vs. simple inheritance

design-patterns, inversion-of-control

Solution

The decorator pattern concerns composing an object. To be able to inherit the type of that object, it must obviously be inheritable. Not all types are designed for inheritance, i.e., meant to be base classes, even if they from a purely technical viewpoint can be inherited (which I consider a design flaw).

The raison d'être for the decorator pattern is to be able to modify the behavior of objects without modifying the objects themselves. By inheriting, you're essentially modifying the object itself and what you get then is regular behavioral change through polymorphism, meaning that you did not accomplish the same thing.

So, both decoration and inheritance has their uses. Use decoration when anyone of these is true

- you can not inherit (for example if the class is `sealed` in C#)

- you should not inherit (the class is obviously not meant to be a base class)

- you want to change the behavior of one particular object many times (by wrapping it with decorators of different behavior)

Note that inheritance is the most powerful tool there is in the OO toolbox. With great power comes great responsibility and that's not always easy to cope with. I'd say: Always compose or aggregate. When that just cannot be done, inherit. If you can't inherit, try harder to compose or aggregate."

Problem

Can someone please walk me through the differences between (as in benefits of) creating decorator classes using constructor injection of another class as opposed to class inheritance? In the examples I can think of, I might accomplish the same end goal in one of two ways but I suspect I am missing something fundamental.

Original source

Related problems