Jean Paul's Blog

There are 2 types of People in the World, One who Likes SharePoint and..

  • Microsoft MVP

  • MindCracker MVP

  • CodeProject MVP

  • eBook on SharePoint 2010

  • eBook on Design Patterns

  • eBook on Windows Azure

  • NLayers Framework @ CodePlex

  • MSDN Forums

  • .Net vs. Java

    Due to Public Demand

Posts Tagged ‘strategy design pattern’

Strategy Pattern

Posted by JP on November 13, 2011

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

Scenario
In a simple shooting game, the player can select between two different guns
1) Pistol which is having 5 bullets and the graphics and animation is different
2) Grenade Launcher which is having 20 bullets and the graphics and animation is different
In the normal coding scenario, if the gamer changes the gun we have to do lot of if conditions
in the fire method, in the draw gun method, in the bullet animation methods.
We can avoid the above complications by switching to the famous Strategy pattern.
Extract the difference implementations into appropriate classes and switch between the classes.

Screenshot


Code Explained

The core classes involved are:

  • Gamer
  • PistolGun implementing IGun
  • GrenadeLauncher implementing IGun

Whenever the user changes the gun the Gamer.Gun property is switched between
PistolGun and GrenadeLauncher instances.
Here the IGun interface extracts the part which differ for different guns.

The Gamer class which maintains the Gun and refreshes the picturebox would be looking like:

01
public class Gamer

02
{

03
private PictureBox _gunBox;

04

05
public Gamer(PictureBox gunBox)

06
{

07
_gunBox = gunBox;

08
}

09

10
private IGun _gun;

11

12
public IGun Gun

13
{

14
get { return _gun; }

15
set { _gun = value; RefreshGunInfo();  }

16
}

17

18
private void RefreshGunInfo()

19
{

20
_gun.Draw(_gunBox);

21
}

22

23
public void Fire()

24
{

25
_gun.Fire();

26
}

27
}

Advantages
Strategy pattern helps us to make the code more cleaner, highly object oriented and easier to manage and extensible.

The associated source code can be found here.

Advertisements

Posted in C#, Design Patterns | Tagged: | Leave a Comment »