Search code examples
javaphpdesign-patterns

Duck example strategy pattern - Head first design pattern


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

  1. Problem enter image description here

  2. the conclusions enter image description here

He said "when joe added new behavior to the duck superclass, he was also adding behavior that was not appropiate for sume Duck subclasses"

BUT in the conclusion he added performFly() and performQuack(); what is the different because i think it same with he was also adding behavior that was not appropiate for sume Duck subclasses?

**image taken from the book Head first design pattern ** this question doesn't state this book is not good, this book is really good in my opinion. this is just me who is asking something that I didn't get from the book.


Solution

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