Simple Strategy Pattern example in java - strategy design pattern

Simple Strategy Design Pattern example in java


Before looking at the example of strategy design pattern, we will see what is the need or intent of strategy pattern, this will help us to understand the example.

1. First intent of strategy design pattern is to make algorithms vary independantly.
2. To achieve the varying algorithms , we need to have a family of algorithms and encapsulate each family as an object, and make them interchangeable.
3. If we have different classes differenciated by only the algorithm, so these algorithm can be encapsulated.
4. If our class has many behaviours which are separated by multiple conditional statements such as if this do this , if that do that etc. but using strategy design pattern we can encapsulate each behaviour using strategy.

Now I hope you have got the general idea about the Strategy Design Pattern.

Now lets understand more using this simple strategy design pattern example or simple strategy pattern example :

In following simple example of strategy pattern in java, we need to encapsulate the algorithms and behaviours and use them interchangably. In the following example, lets see there are ways to travel such here are by air or by bus by train etc. So these are the strategies for travel. Now lets see how we are implementing it in java :

We are declaring the algorithm signature in an interface.


public interface TravelWay {

public void travel();

}



2. We are putting the behaviour into derived classes as below :


public class ByAir implements TravelWay {

public void travel(){

System.out.println("Travelling via air");

}

}


public class ByRoad implements TravelWay {

public void travel(){

System.out.println("Travelling via road");

}

}


Object who will use the strategies.


public class Tourist {

TravelWay travelMode;

String name;



public Tourist(String name ){

this.name = name;

}

public void setTravelMode(TravelWay travelMode){

this.travelMode = travelMode;

}

public void travel(){

this.travelMode.travel();

}

}


Use of strategy pattern :


public class TouristRecord {



public static void main(String[] args){

Tourist t1 = new Tourist("John");

Tourist t2 = new Tourist("Allen");

t1.setTravelMode(new ByRoad());

t2.setTravelMode(new ByAir());

t1.travel();

t2.travel();

}


}


Hope you liked the Simple strategy pattern example.
Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment