I’ve read the decorator design pattern from Wikipedia, and code example from this site.
I see the point that traditional inheritance follows an ‘is-a’ pattern whereas decorator follows a ‘has-a’ pattern. And the calling convention of decorator looks like a ‘skin’ over ‘skin’ .. over ‘core’. e.g.
I* anXYZ = new Z( new Y( new X( new A ) ) );
as demonstrated in above code example link.
However there are still a couple of questions that I do not understand:
-
what does wiki mean by ‘The decorator pattern can be used to extend (decorate) the functionality of a certain object at run-time‘? the ‘new …(new… (new…))’ is a run-time call and is good but a ‘AwithXYZ anXYZ;’ is a inheritance at compile time and is bad?
-
from the code example link I can see that the number of class definition is almost the same in both implementations. I recall in some other design pattern books like ‘Head first design patterns’. They use starbuzz coffee as example and say traditional inheritance will cause a ‘class explosion’ because for each combination of coffee, you would come up with a class for it.
But isn’t it the same for decorator in this case? If a decorator class can take ANY abstract class and decorate it, then I guess it does prevent explosion, but from the code example, you have exact # of class definitions, no less…
Would anyone explain?
Let’s take some abstract streams for example and imagine you want to provide encryption and compression services over them.
With decorator you have (pseudo code):
With inheritance, you have:
with decorator, you combine the functionality at runtime, depending on your needs. Each class only takes care of one facet of functionality (compression, encryption, …)
in this simple example, we have 3 classes with decorators, and 5 with inheritance. Now let’s add some more services, e.g. filtering and clipping. With decorator you need just 2 more classes to support all possible scenarios and combinations, e.g. filtering -> clipping -> compression -> encryption.
With inheritance, you would have to provide a class for each combination – more than 60 classes.