I'm not able to understand the following from the HFDS book! Page 21 says that
Duck model = new ModelDuck(); model.performFly(); model.setFlyBehavior(new FlyRocketPowered()); model.performFly();
And there is a small comment below it that says "If it worked, the model duck dynamically changed its flying behavior! You can't do that is the implementation lives inside the duck class." Can anyone justify this me please?? What they mean by saying "implementation lives inside the duck class"
If the ModelDuck performFly() method had code to flap wings you couldn't change how a Duck flies without changing the ModelDuck class itself. I'm sure that's what they meant by "implementation lives within the duck class."
But ModelDuck apparently delegate its flying to a FlyBehavior class. The default FlyBehavior might well flap wings. But in that sample code snippet we plug in a brand new version of FlyBehavior with rocket packs. Now our Duck flies with rockets.
We can add new behaviors without touching the Duck class, and we can change the FlyBehavior as often as we want in a running program. Very cool stuff!
Makes me think of the Matrix where somebody could download the skills to fly a helicopter.
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi