简体   繁体   中英

'Head First Design Patterns: Decorator example IS-A and HAS-A confusion

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:

Head First 设计模式:装饰器 UML

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:

  • a 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).
  • 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM