Duck example strategy pattern - Head first design pattern

前端 未结 4 1459
鱼传尺愫
鱼传尺愫 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:42

    The strategy pattern works when you favor composition over inheritance http://en.wikipedia.org/wiki/Composition_over_inheritance

    This is a good practice because you can change the behavior of a class without having to change any code. And you don't need a huge tree of classes either. You also can change the behavior of a class dynamically.

    What it does in the example is that defines "behaviors" in the parent class. In the parent class you define that a Duck can have a flying behavior and a quacking behavior. But it doesn't mean the children classes have to have quack or fly.

    You can have a nonflying duck and when you call "fly" it will do nothing because we'll have a "non-flying" behavior.

    Instead of hardcoding what a duck does in the class, you can change the behavior of this duck whenever you want.

提交回复
热议问题