I was reading about the Strategy design pattern in java. The problem is set as follows
You have a duck class and several types of ducks. You have to code in the flying and quacking behaviors of the ducks. You obviously cannot code in the flying, non-flying behaviors in each of the duck class methods especially if you have like a 100 different kind of ducks. So you create a behavior interface called FlyingBehavior
and QuackingBehavior
and have implementations like NonFlyingBehavior
or FlyWithWingsBehavior
or MuteQuackBehavior
or SqueakQuackBehavior
. Then set these in a field in the different classes of duck. That way you associate the behaviors with the ducks.
What I don't understand is why it has to be done with a composition and why not with inheritance. Why can't you create subclasses lke NonFlyingDuck
, FlyWithWingsDuck
or SqueakingDuck
, MuteQuackingDuck
and so on, and then implement the methods fly()
or quack()
and then assign appropriate behavior to the ducks. Is this because multiple inheritance is not supported. so if you have a non-flying, squeaking duck then you cannot extend both squeakingDuck
and NonFlyingDuck
or is it something else. Is there some way of doing this with inheritance?
I feel a bit confused. The motto is 'favor composition over inheritance'. Why though?
Can someone explain this in depth?