I'm trying to get my head around design patterns. I think they may be one step too advanced in my programming abilities as I am struggling quite a bit with them, however my university assignment is to apply them. So here I am.
I am going through the example of the Decorator Pattern from the Head First book. This is the example:
As you can see in the diagram, the CondimentDecorator has the IS-A and HAS-A relationship with Beverage . However, here is the code they write for the CondimentDecorator and one of the condiments, Mocha :
In the CondimentDecorator class the only thing that it contains is a method getDescription .
It's the Mocha class that contains instantiates the Beverage class AND calls getDescription .
So doesn't this mean that it's the Mocha class that has a IS-A and a HAS-A relationship?
The decorator pattern is indeed not easy to grasp when learning OOP: it uses inheritance and object composition together to offer something that looks like dynamic inheritance but is mostly based on composition. In addition, the example uses several levels of inheritance, which makes it even more complex to grasp.
The idea in this design, is twofold:
Mocha
is a CondimentDecorator
that you can use it everywhere where a CondimentDecorator
is expected. Moreover, since a CondimentDecorator
is a Beverage
, you can also use a Mocha
everywhere where a Beverage
is expected. This is the purpose of the inheritance in this design (IS-A).CondimentDecorator
object (such as a particular Mocha
) knows a Beverage
object that it enriches with additional responsibilities, acting as intermediary: it deals a "front-end" to the external world, and enriches the behavior of the other objects by doing additional things in addition to forwarding calls. This is the purpose of the association which is implemented in a code with object composition (ie Beverage beverage
) - (HAS-A, but this terminology might be misleading).To understand better how it works, especially the second part you should not just reason with classes: you'd better play a scenario with objects and see how the involved instances cooperate. Also use some scenarios, where the beverage object is in fact itself a decorator.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.