0

I came across this article: http://sourcemaking.com/design_patterns/decorator

After reading it, I am having a little bit of difficulty understanding a concept. If you look in the Structure section in that article when it shows the UML class diagram, I am confused on why the Option Wrapper class extends the Interface class but the Option Wrapper class has an instance (composition) of the Interface class as well. Why are both of these relationships needed to in order to accomplish what the Decorator Pattern hopes to do? In other words, why is neither relationship good enough by its self?

5

Decorators usually augment the original functionality in some way, not replace it altogether. So they need to hold a reference to the original object. For example, a decorator that adds memoization to a function will need to be able to call the original function if its result is not found in the cache.

However, the calling code should not need to know if it's working with a decorated class or the original class. That means the decorator needs to implement the same interface as what it decorates.

  • In that article, a rule of thumb: "Decorator supports recursive composition" . This I think informs the "why" of the question. Then here: the Composite pattern we see a very similar design - the difference being that black (or not) diamond - aggregation vis-a-vis composition. So, yeah, "recursive composition." – radarbob Mar 27 '15 at 21:23
2

Just think of a decorator as having 2 functions:

  • adds/modifies the functionality of the original class. In order to do so, it needs to have reference to the original class, and therefore need to have composition.
  • look the same as original class to the client. By look the same, I mean from the client's perspective, they will not know and don't need to know which class is decorator, which class is original class. In order to look the same, it needs to offer the same set of public functionality from the same contract like original class. That's why it needs inheritance

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.