• Post Reply Bookmark Topic Watch Topic
  • New Topic

Head First Design Pattern Strategy Pattern  RSS feed

 
Mahtab Alam
Ranch Hand
Posts: 391
1
Java MySQL Database PHP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was reading Head First Design Pattern book .

They have explained one scenario which I think you guys might already know.

I am going to repeat it so that I can ask my question.

There is a Duck class and lots of Subclasses of that MalardDuck RedBlackDuck HenDuck etc.

Now some of the ducks can fly , so where we should put fly method.

We can put it inside Superclass Duck that will be bad since there are lots of duck that can`t fly , so if we put fly method inside Duck superclass
Its wrong although we can go in each sub class and can override the fly method saying "I can Fly" or "I can`t fly".

So they introduce this analogy create an interface ICanFly so now only those ducks that can fly will implement ICanFly interface.
That looks very good , So only those ducks that actually fly will have fly method and they can implement the way they want.

But then they say this is bad since there is no code reuse.

In this design what kind of code reuse we are looking .





 
Mahtab Alam
Ranch Hand
Posts: 391
1
Java MySQL Database PHP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think I can see the no code reusability problem say there are different ducks and flying behaviors like FlyFast ,FlySlow, FlyRound , FlyCircular , FlyStraight

Now say there are three ducks that fly in circular fashion , I have to duplicate the same code in all those three ducks.

There is no code reuseability.

 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mahtab Alam wrote:In this design what kind of code reuse we are looking .

None, because interfaces don't contain code (at least, not before version 8 ).

What you have is behavioural inheritance. Any Duck (or Insect) subclass that implements a Flying interface will be required to implement a fly() method before it can be created.

HIH

Winston
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!