In conclusion, he adds two new classes that have a fly() function. However, the function does not always make the duck fly. Rubber ducks cannot fly, so they use an instance of the FlyNoWay class. Other ducks that can fly use an instance of the FlyWithWings class. The flyBehavior field in the Duck class is likely to be set in the constructor.
The performFly() function will call the fly() function for any class.
As kainaw pointed out in the comments, this is a rather complicated solution. However, it can still be used. Say you are creating a duck design program. If the user chooses whether the duck can fly, it cannot be hardcoded. You can create a boolean, but you may have to handle more complex situations, such as behavior. You may need the WildDuckBehavior and DomesticDuckBehavior WildDuckBehavior , each with their own information on how to proceed. Basically, the example in the book is a simplified version of how this will be used.
source share