Duck example strategy pattern - Head first design pattern

前端 未结 4 1458
鱼传尺愫
鱼传尺愫 2020-12-16 22:01

I want to ask something about duck example on this book that made me confused and I feel contradictions.

  1. Problem

4条回答
  •  星月不相逢
    2020-12-16 22:33

    In the conclusion, he is adding two new classes that have a fly() function. However, the function does not always make the duck fly. Rubber ducks can't fly, so they use an instance of the FlyNoWay class. Other ducks that can fly use an instance of the FlyWithWings class. The field flyBehavior in the Duck class would probably be set in the constructor.

    The function performFly() would call the fly() function for whatever class is chosen.

    As stated by kainaw in the comments, this is a rather complicated solution. However, it can still be used. Say that you are creating a duck designing program. If the user chooses whether the duck can fly, it can't be hard coded. You could create a Boolean value, but you might need to handle more complicated situations like behavior. You might need a WildDuckBehavior class and a DomesticDuckBehavior, each with its own information about how to act. Basically, the example in the book is a simplified version of how this would be used.

提交回复
热议问题