Duck example strategy pattern - Head first design pattern

The strategy pattern works when you favor composition over inheritance http://en.wikipedia.org/wiki/Composition_over_inheritance

This is a good practice because you can change the behavior of a class without having to change any code. And you don't need a huge tree of classes either. You also can change the behavior of a class dynamically.

What it does in the example is that defines "behaviors" in the parent class. In the parent class you define that a Duck can have a flying behavior and a quacking behavior. But it doesn't mean the children classes have to have quack or fly.

You can have a nonflying duck and when you call "fly" it will do nothing because we'll have a "non-flying" behavior.

Instead of hardcoding what a duck does in the class, you can change the behavior of this duck whenever you want.


I'm not a guru of design patterns, but while I was reading that book, the first sensation I had about that particular chapter was that the way interfaces was built and then implemented, violated one of the well know programming principle: the Interface Segregation Principle (ISP) Basically this principle state that

no client should be forced to depend on methods it does not use

Because some Ducks that don't fly implement the fly() method even it they don't need it. That said, I think that in this particular case it is unavoidable to implement all the interfaces methods since on the client side we're using polymorphic behaviors, and we need to be sure that we have all the methods available even if unused.