samedi 19 octobre 2019

Composition over Inheritance(step into Design pattern)

So I have started learning book called head first design pattern and in its initial chapter it has given a scenario where composition is preferred over inharitance with a duck class example.

public abstract class Duck
{
   Swim()
       { 
          //all ducks can swim same way
       }
   abstract Look();// ducks can look different
}

So above duck class inherited by different types of ducks and also by some fake rubber duck.

(Based on duck type)

      Duck obj=new IndoDuck();
         //Or
     //Duck obj =new MallardDuck();

     obj.Swim();
     obj.Look();

So till now it looks good.

Now the change come to add a Flying behaviour to the ducks.

We cant just add fly method behaviour to the abstract duck class as there are fake ducks availbe who cant fly.

So author create a IFly interface which will be implemented by Flyable class and NonFlyable class.

interface IFly
{
 Fly();
}

Flyable: IFly
{
 Fly()
{
  // can fly
}
}

NonFlyable:IFly
{
 Fly()
{
  // cant fly
}
}

So this IFly interface will not be implemented by all the different ducks class as this will be a massive change to add flyable/non flyable behaviour to these ducks. So inharitance seems not a good idea here agree.

Author suggests IFly interface will be used inside the Duck class as composition.

public abstract class Duck
{
   Swim()
       { 
          //all ducks can swim same way
       }
   abstract Look();// ducks can look different

IFly Fly();
}

So now what i can do is.

      Duck obj=new IndoDuck();
         //Or
     //Duck obj =new MallardDuck();

     obj.Swim();
     obj.Look();
obj.Fly =new Flyable();
//or
obj.Fly=new NonFlyable();

so my questionis how would i know based on type if Flyable functionality to add or NonFlyable as somewhere i have to tell my each and every duck class that either they fly or they not right?? So how does composition actually solving the problem here i cant relate or i missed something?? Please help.

Aucun commentaire:

Enregistrer un commentaire