Monday, June 9, 2008

Strategy Pattern in Action

Let’s start with describing problem in hand. To be more towards BDD side, let’s define current context.

Here is the requirement cheat that we received from our client.

  • An Eagle is a Bird.
  • A Parrot is a Bird.
  • A Crow is a Bird.
  • A Sparrow is a Bird.
  • All Bird can fly.
  • Eagle and Crow fly the same way i.e. they print “FAST FLY” when the method is invoked.
  • Parrot and Sparrow fly the same way i.e. they print “SLOW FLY” when the method is invoked.
  • All birds eat.
  • Eagle and Parrot Eat the same way i.e. they print “EAT GRASS” when the method is invoked.
  • Crow and sparrow eat the same way i.e. they print “EAT FRUITS” when the method is invoked.

Our goal is to implement this, with in most maintainable fashion or call it best possible solution, which we can think of.

Sounds simple, isn’t it?

All we need is one interface, call it IBird, with fly and eat method. And then Eagle, Parrot, Crow and Sparrow will implement this interface. Base on our current thinking, our class diagram looks something like this:














public interface IBird

{

string Fly();

string Eat();

}

public class Eagle : IBird

{

public string Fly()

{

return "FAST FLY";

}

public string Eat()

{

return "EAT GRASS";

}

}

public class Parrot : IBird

{

public string Fly()

{

return "SLOW FLY";

}

public string Eat()

{

return "EAT GRASS";

}

}

public class Crow : IBird

{

public string Fly()

{

return "FAST FLY";

}

public string Eat()

{

return "EAT FRUITS";

}

}

public class Sparrow : IBird

{

public string Fly()

{

return "SLOW FLY";

}

public string Eat()

{

return "EAT FRUITS";

}

}

Wait a minute!! Are we sure this is best possible thing we can do here? Is this most maintainable/flexible solution that we can possibly have??

Let’s think over this!!!

Aren’t we repeating our self when we implement Fast Fly method in Eagle as well as Crow? Same thing goes for slow fly, eat grass and eat fruit method too. Clearly, we have more than one instance of our algorithms. So it fails on maintainability test (because now we have to remember that every time we change something or fixes some issue, we have to do it at two places)

Let’s run flexibility test now. Our client has come up with following new requirement

A Plane is not a bird.

Plane fly the same way as Eagle and Crow i.e. it print “FAST FLY” when the method is invoked.

Hmmm….. Since we have same behavior as in bird, how about implementing IBird and thereby get the behavior.







public class Plane : IBird

{

public string Fly()

{

return "FLY FAST";

}

public string Eat()

{

throw new System.InvalidOperationException();

}

}

STOP!!!! Does this make sense? C’mon… after all, plane is not a bird. And what does it eat? May be fuel, but our client didn’t specified any requirement related to that. One option could be to leave it as not implemented though.

Grrrrrrrrr!!! You are now violating ISP. Sounds like we are failing on this test too... Shame on us, couldn’t clear even one test.

We need help. F1 please!

Somebody is knocking our door. Let me go and open the door.

Me: Hey, who is there?

Voice from outside: Hey it’s me, Strategy pattern. I heard you screaming for help. I think I can help you. May I come in?

Me: hmmm… sure, why not? So why do you think you can help me with solving my problem?

Strategy Pattern: Well, you see, you are trying to put everything in inheritance base model and that is why you are falling in trap. Rather you can use compositional approach.

Me: ha ha ha… that’s too much jargon, just like Microsoft help. Now can you come to the point and tell me how to solve my problem, instead?

Strategy Pattern: Sure, lets re-consider our approach to this problem here. From the description, it is clear that we are talking about two different set of behavior, Flying and Eating, right?

Me: Ya, I can see that as well.

Strategy Pattern: ok, so lets define two interface called ICanFly and ICanEat, to represent them.

Me: sounds good to me.

Strategy Pattern: Now since we have Fast flyer and Slow flyer, we can implement them in class called FastFlyer and SlowFlyer respectively.

Me: Go on

Strategy Pattern: And then, we have FruitEater and GrassEater , which implement ICanEat. That makes our class diagram look like this:














public interface ICanFly

{

string Fly();

}

public interface ICanEat

{

string Eat();

}

public class FastFlyer : ICanFly

{

public string Fly()

{

return "FAST FLY";

}

}

public class SlowFlyer : ICanFly

{

public string Fly()

{

return "SLOW FLY";

}

}

public class GrassEater : ICanEat

{

public string Eat()

{

return "EAT GRASS";

}

}

public class FruitEater : ICanEat

{

public string Eat()

{

return "EAT FRUITS";

}

}

Me: I am with you. Carry on

Strategy Pattern: Finally, Eagle is fast flyer and eats grass so why not let it implement ICanFly and ICanEat interfaces. In our implementation of Fly, we will delegate this task to FastFlyer and for Eat we will delegate to GrassEater.

Me: Now you are going to tell, we can do same thing for Parrot, Crow and Sparrow too, right?

Strategy Pattern: you are smart! So that gives us new picture like this:














public class Eagle : ICanFly, ICanEat

{

public string Fly()

{

return new FastFlyer().Fly();

}

public string Eat()

{

return new GrassEater().Eat();

}

}

public class Parrot : ICanFly, ICanEat

{

public string Fly()

{

return new SlowFlyer().Fly();

}

public string Eat()

{

return new GrassEater().Eat();

}

}

public class Crow : ICanFly, ICanEat

{

public string Fly()

{

return new FastFlyer().Fly();

}

public string Eat()

{

return new FruitEater().Eat();

}

}

public class Sparrow : ICanFly, ICanEat

{

public string Fly()

{

return new SlowFlyer().Fly();

}

public string Eat()

{

return new FruitEater().Eat();

}

}

Me: Wow, you see that solves my problem, because I am no more repeating my algorithm here. It’s been implemented at just one place

Strategy Pattern: Of course. Do you see any other benefit too?

Me: Hmmm. Let me think………………….

Me: Yes, you see, now I can have plane which implements only ICanFly interface and I am going to delegate actual implementation to FastFlyer again.

Strategy Pattern: right, that gives you







public class Plane : ICanFly

{

public string Fly()

{

return new FastFlyer().Fly();

}

}

Me: And it also passes my second test of flexibility because I could change my design to accommodate new enhancement, very easily.

Strategy Pattern: There you go.

Me: Thank you so much strategy pattern. I am glad that you came here and taught me such an important lesson.

Strategy Pattern: I am glad too, that I could be of some use.

Me: Last thing, I would like to ask though, how do I recognize you in future? Do you have any formal identity?

Strategy Pattern: Oh ya, I am defined as

“Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.”

Me: sounds great, and once again thanks for this valuable lesson. I guess we will meet again very soon J

Strategy Pattern: bye bye, and Develop smartly J

-------------------------------------------------X-------------------------------------------------

That was end of my first session on the ongoing series of blog about design pattern. I am planning to upload all my code sample on google code repository. So watch out at http://feeds.feedburner.com/MahendraMavani for more update.

Also, along with my colleague, John Teague, I am going to record screen cast on strategy pattern. This screen cast will briefly cover what I have discussed here and then we will jump to real life usage scenario of strategy pattern in action.

Disclaimer: I am not claiming to be design pattern expert. This is just 2 cent from my side to feel the ocean. I welcome comments, suggest, concern, query and healthy argument on this post. Please feel free to drop your opinion in the comment section.

25 comments:

Anonymous said...

Its very good...Keep up ur gud work

Gogu De La Gaze said...

Great job! Very easy to understand, thank you.

Anonymous said...

видео девушка трахает конь
секс талк
жесткий анальный секс бесплатно
монтаж видео бесплатно
тяжёлый секс
16 летние секс
секс коробка передач
трахаться покажите
спящие порно видео
скачать порнофильм школьницы

Anonymous said...

Nice dispatch and this enter helped me alot in my college assignement. Thank you seeking your information.

Anonymous said...

Opulently I acquiesce in but I contemplate the brief should secure more info then it has.

Anonymous said...

And how it to paraphrase?

Anonymous said...

The happiness to me has changed!

Anonymous said...

Hi,

When ever I surf on web I come to this website[url=http://www.weightrapidloss.com/lose-10-pounds-in-2-weeks-quick-weight-loss-tips].[/url]You have really contiributed very good info here mahendramavani.blogspot.com. Frankly speaking we really do not pay attention towards our health. In plain english I must warn you that, you are not serious about your health. Recent Scientific Research indicates that closely 80% of all USA grownups are either chubby or overweight[url=http://www.weightrapidloss.com/lose-10-pounds-in-2-weeks-quick-weight-loss-tips].[/url] Therefore if you're one of these citizens, you're not alone. Its true that we all can't be like Brad Pitt, Angelina Jolie, Megan Fox, and have sexy and perfect six pack abs. Now the question is how you are planning to have quick weight loss? [url=http://www.weightrapidloss.com/lose-10-pounds-in-2-weeks-quick-weight-loss-tips]Quick weight loss[/url] is not like piece of cake. If you improve some of your daily diet habbits then, its like piece of cake to quickly lose weight.

About me: I am blogger of [url=http://www.weightrapidloss.com/lose-10-pounds-in-2-weeks-quick-weight-loss-tips]Quick weight loss tips[/url]. I am also health expert who can help you lose weight quickly. If you do not want to go under difficult training program than you may also try [url=http://www.weightrapidloss.com/acai-berry-for-quick-weight-loss]Acai Berry[/url] or [url=http://www.weightrapidloss.com/colon-cleanse-for-weight-loss]Colon Cleansing[/url] for effective weight loss.

Anonymous said...

Вопрос:   Я очень хочу встретиться с адекватной девушкой. Времени после учебы абсолютно не хватает, а в выходные обычно приходится тоже  вкалывать. В общественных местах знакомиться не удобно.  Пока на сайтах знакомств вижу  обычно продажных женщин. Посоветуйте решение этой проблемы, пожалуйста. Наперед искреннее спасибо !!!.

Anonymous said...

Шины и диски на любой вкус shinway ru. Я заказал шины goodyear ultragrip-500, вопервых оказалась дешевле чем в аналогичных магазинах, а вовторых доставили очень быстро несмотря на то, что я живу в Питере, а магазин в Новосибирске. Всем рекомендую очень хороший [url=http://www.shinway.ru/]интнрнет-магазин[/url].

Anonymous said...

Hi, welcome to anaglyph erotic 3D website http://www.eromania3d.ru

Anonymous said...

Наши сайты:
Сентябрь05 Koh Chang Kacha Resort and Spa RESIDENCES CANNES VILLA FRANCIA Hotel Padma Hesperia Centurion The Royal Santrian Kymata Sherwood Breezes Resort Ferienpark Worthersee Август14 Сентябрь15 Zastava 128 Skala 2004 Perodua Kenari 1992 Skoda 105120 (744) 1993 Lincoln Navigator 58700 2008 Август15 Tofas Kartal 5 20600 2005 Marcos Mantula Martina Mantara 0.8 92100 1999 Chevrolet Trans Sport 5.8 1998 Август25 Wellington Grange Artefes Сентябрь30 das Isuzu Axiom 4.3л 1990

Anonymous said...

Вот новые фильмы что я нашла в нете из рабочих

Anonymous said...

Варез - качай всё бесплатно.

Anonymous said...

8q9ij0bmm

Here is my web-site :: Short term payday loans

Anonymous said...

http://bhakfocadeath1975.tk/checked/anketa/82271 Оценки Лена, Москва, (916)8759286
http://deiwaltare.tk/ind/anketa47565.htm#tp33740?sr=kolmess#linkreport Проститутки M. Авиамоторная - Индивидуалка Вероника, +7 (917) 575-86-97
http://burrighchipve.tk/mass/anketa88811.htm Массажистка Кристина&Лера, M. Марьина Роща - Район СВАО Марьина Роща, +7 (905) 786-79-97
http://krawindaibull.tk/checked/anketa/78264 Оценки Даша, Москва, не доступен
http://jockinsrinti.tk/ind/anketa85098.htm Проститутки M. Автозаводская - Индивидуалка Инга, +7 (962) 952-72-56

Anonymous said...

http://lyuscenavfas.tk/comments/anketa/78351 Отзывы о девушке Аннэт, Санкт-Петербург, (981)7316059
http://condgaratfi1981.tk/ind/anketa83922.htm Проститутки M. Алексеевская - Индивидуалка Лиза, +7 (985) 218-77-09
http://deiwaltare.tk/mass/anketa57491.htm Массажистка Оля, M. Бабушкинская - +7 (968) 703-98-19
http://lippprinpere.tk/ind/anketa81614.htm Проститутки M. Сокол - Индивидуалка Настя, +7 (915) 263-09-54
http://condgaratfi1981.tk/ind/anketa74002.htm Проститутки Индивидуалка Lena, +7 (968) 850-71-65

проститутки владыкино

Anonymous said...

I incentive rappresentano una delle pi grandi opportunit per i giocatori already been functional with consistently, signification that the computer software has the power to alteration the mode in which how it operates. [url=http://www.tasty-onlinecasino.co.uk/]online casino[/url] online casino about of the Loose online Keno for an extended time, you moldiness infer the professional strategies that players use. http://www.tasty-onlinecasino.co.uk/

Anonymous said...

In most cases, companies might be able to the company give the eco-friendly light towards the application [url=http://www.ubyvk.co.uk/]1 year loans[/url] long term loans uk Eighty to Seven hundred and fifty with the accommodating repayment period of 2 weeks to help 4 weeks http://www.your12monthloans.co.uk/

Anonymous said...

Bien sûr, le fait même que vaping est utilisé pour prévenir tout accident inhalation. [url=http://www.cigaretteelectroniquex.co.uk]cigarettes electroniques[/url] ecigarette Cela peut vous donner mani?Re la mode de fumer. http://www.excellentecigaretteelectronique.fr

Anonymous said...

Frapper les fumeurs à rester dans la même pièce sans aucun problème. [url=http://www.cigaretteelectroniqueco.co.uk]cigarette electronique[/url] e cig La communauté médicale dans son ensemble, les équipes de dollars et a généré plusieurs millions de dollars d'activité par des entreprises commerciales réputées. http://www.cigaretteelectroniquefab.co.uk

Anonymous said...

J'ai essayé plusieurs fois d'arrêter de manière Cowboy, Rambo, Godfather III, 50/50 et Rocky IV. . [url=http://www.cigaretteelectroniquex.co.uk]cigarette electronique[/url] cigarette electronique Le tout sur quatre implants dentaires vous donner des dents substitués implant pris en charge qui n'est pas entre deux bouchées et stages, engager la conversation. http://www.cigaretteelectronique1.co.uk

Anonymous said...

The surgery is much less expensive than IVF at about $7000 or less per procedure. Also keep a record of the days you think you are ovulating and the times you and your partner make love. But, you need to be very careful before planning the second pregnancy.
http://www.pregnancyhelper.in

Anonymous said...

[url=http://www.adeanphotography.com/]Fake Oakleys[/url] How niceprettycoldfunnystupidboringinterestingI have my hair cut every month.What you need is just rest. I'm usually just using the search engines to look up information.Don't be so modest.What I want to do is different from those of others.What I want to do is different from those of others.I have a surprise for you.Mother doesn't make up.They are arguing over who should pay the bill.

[url=http://www.resorthomesgalveston.com/]Fake Oakley Sunglasses[/url] He was born in New York.The show is supposed to be goodGo right back to the beginning. Today it is common that women and girls make up in public.Don't keep me waiting long.Were there any exciting incidents during your journey? What shall we do tonight? Great efforts ensure the success of our work.I'm in a hurry!It's not as cold hot as it was yesterday

[url=http://www.grnbuildersinc.com/]Cheap Oakley Sunglasses[/url] How do you like our English literature Prof.None of your business!I walked across the park. How can I climb up that wall!Just wonderful!I'll furnish my house with furniture.I'll furnish my house with furniture.I beg your pardon.He strolls about the town.I believe I haven't reached the summit of my career.

Anonymous said...

These merchants are able to do hence because large retailers can no longer yourself on the website of your money lenders London Business Angels UK This will keep the interest payments decrease and the financial institution will have no reason at all to claim your vehicle