.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month

Home >> Articles >> Architecture/Pattern >> Post New Resource Bookmark and Share   

 Subscribe to Articles

Strategy Pattern explained using a shooting game

Posted By:Jean Paul       Posted Date: September 30, 2010    Points: 50    Category: Architecture/Pattern    URL: http://www.dotnetspark.com  

In this article I am trying to demonstrate the power and flexibility of Strategy design pattern.


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.

Definition of Strategy Pattern
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"


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:
public class Gamer
    private PictureBox _gunBox;

    public Gamer(PictureBox gunBox)
        _gunBox = gunBox;

    private IGun _gun;

    public IGun Gun
        get { return _gun; }
        set { _gun = value; RefreshGunInfo();  }

    private void RefreshGunInfo()

    public void Fire()

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


 Subscribe to Articles


Further Readings:


No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend