Saturday, February 27, 2010

Strategy Pattern

Few weeks back I started reading about Design Patterns and Madhur kept on nagging (he reads it as encouraging) me to blog about it. So, I am kicking off a series of blogs on design patterns, starting with the Strategy Pattern.

As the name suggests, the pattern deals with how to organize different strategies in your application. Before starting with the pattern, following are the basic principles that one needs to grasp:
1. Encapsulate what varies.
2. Favor composition over inheritance.
3. Program to interface than implementation.

So, let me formally introduce you the Strategy Pattern, it is a design solution wherein you combine a family of algorithms, organize it separately in interfaces, prepare it concrete implementation and in your client-code work exclusively with the interface.

Let me give you an example, suppose there is a base class animal with concrete implementation as in dogs, leopard, fish etc. All these animals exhibit moving behavior, but differently as in walking or leaping or swimming. Thus, we can write a interface MovingBehavior with move as its method. It should have WalkingBehavior, LeapingBehavior and SwimmingBehavior as concrete implementations. The base class Animal would maintain a MovingBehavior reference with getter and setter method. Thus, for each animal, we need to specify its corresponding MovingBehavior. It has one more advantage, if our dog decides to swim, we can appropriately set its behavior.

I hope this served as a good introduction to Strategy Pattern. If this blog let you down, you know where to send your hate messages (he thinks good wishes) :-)

PS: I am reading Head First DP, thus the content might appear strikingly similar, its a great book to read, in fact the whole HeadFirst series is awesome.

2 comments:

  1. Good start Bhavin. Looking forward to the series.

    A few suggestions :
    - cite more production / concrete use cases for the pattern. That will make the blog an enhancement to the HFDP chapter.
    - how a about some code, where the implementation is non-trivial??

    And, YES I am Madhur. I don't have this good a blog, but you can read it here : http://madhurtanwani.blogspot.com

    ReplyDelete
  2. Thanks for suggestions bro, i'll try to incorporate them in future.

    ReplyDelete