I want to ask something about duck example on this book that made me confused and I feel contradictions.
he was also adding behavior that was not appropiate for sume Duck subclasses
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.
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.