Design Pattern – Strategy Pattern

Sudhakarj21
Posted by in Design Pattern & Practices category on for Beginner level | Views : 17337 red flag
Rating: 3 out of 5  
 1 vote(s)

This article will help you understand Strategy Pattern in an easy way uses C# code for example
Introduction
 
As explained in my previous article design patterns will help you to resolve problem quickly with already proven solution. Please refer to my previous Article on Why we need design patterns?
Overview of Design Principles

Before we go to Design Patterns we need to understand few Design Principles. Below are some of the principles that are required to understand Strategy Pattern.


1.    Identify what changes in your application and separate it
2.    Program to interfaces, not the implementations
3.    Favor Composition over inheritance

While go through this pattern will show how we can achieve these with Strategy Pattern.
Strategy Pattern

It is most important Pattern in OOD (Object Oriented Design). It helps to achieve greater flexibility to programming complex applications in an easy way. Let’s start with a Problem or Requirement that you want to Design.

Problem: We need develop a game application which has Soldiers in it and we want different actions done by different types of Soldiers. Example Captain, Marine, GroundCommander, AirCommander, Navy Soldier etc… All of them can Attack and Drive Vehicles.


Analysis: So as per requirement I though inheritance is good have a base Soldier and all other types inherit from the base and started my Design as below


 


Now after few more Phases of development we have few more changes that only Commander can Order and Drive Vehicle. But we placed Drive in base so let’s override the Drive method in child classes then why we need drive in base?

Now I thought of using interfaces related to Drive and Order as below and implement which is required.

 

Thought everything looks fine. But there is no reusability of Drive or Order in this design which leads to Maintenance issues in future and if I want to make 50 types of Soldiers it will be a Nightmare to implement all the Drive and Orders for soldiers who can do it.

Now let’s consider the design principle - Identify what varies in the application and encapsulate it.

We know what varies from the Soldier to Soldier i.e. Drive and Order Behaviors. Now we split this Behavior using this Principle.


 

So just implement Soldier removing Drive and Order as below


 

And implement the varying Behaviors. But since the Behavior needs to be attached to Soldier need to Program to an Interface, not for Implementation which is the Second Principle.

 

So now we have Soldiers and now we have different Behaviors we just need to add little code to attach these Behaviors as below and make and now we consider 3rd principle favor composition over inheritance as below.

 

Now at runtime also you can Change Drive and Order behavior by calling SetDrive and SetOrder methods and now the Behavior Logic can be interchanged also. Below is the sample code.



public class Soldier
    {
        private IOrder orderBehaviour;
        private IDrive driveBehaviour;
   
        public virtual void Attack()
        {
        }

        public void SetDrive(IDrive drive)
        {
            driveBehaviour = drive;
        }

        public void SetOrder(SoldiersGame.IOrder order)
        {
            orderBehaviour = order;
        }

        public virtual void Drive()
        {
            driveBehaviour.Drive();
        }

        public virtual void OrderCommand()
        {
            orderBehaviour.OrderCommand();
        }
    }


public class NavySoldier : Soldier
    {
        public NavySoldier()
        {
            SetDrive(new CanDrive());
            SetOrder(new CannotOrder());
        }

        public override void Attack()
        {
        }
    }

    public class AirCommander : Soldier
    {
        public AirCommander()
        {
            SetDrive(new CanDrive());
            SetOrder(new CanOrder());
        }

        public override void Attack()
        {
        }
    }


As shown in the above each child, Class sets it own Behavior at runtime also by client. And here comes the actual definition of this Pattern.

The Strategy Pattern defines a family of Algorithms, Encapsulates each one, and makes them interchangeable. Strategy lets the Algorithms varies from Client to Client.

Conclusion

Strategy Pattern is one of the mostly used Pattern in all the OO Programing Languages. It make your code cleaner with High Quality and easy for Maintainability and Extensibility

Page copy protected against web site content infringement by Copyscape

About the Author

Sudhakarj21
Full Name: Sudhakar Kottapalli
Member Level: Bronze
Member Status: Member
Member Since: 10/5/2009 7:05:50 AM
Country:



Login to vote for this post.

Comments or Responses

Posted by: Vuyiswamb on: 3/2/2011 | Points: 25
Good Article, though you lost me somewhere in the article

Login to post response

Comment using Facebook(Author doesn't get notification)