Kakashi Kakashi - 1 year ago 231
PHP Question

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download