Design Patterns: Strategy

java-design-patterns
This time I want to talk about Strategy design pattern. In this way I start articles about behavioral design patterns. These kind of patterns represent some schemas of interaction between objects to make a code more flexible and well organized.The most essential point of this approach is loose coupling between objects.

The Strategy should be used when you have several implementations for one purpose in your application. In this case you create strategy-interface, concrete realizations of the interface, and finally a context class which will encapsulate all logic in some methods. In order to understand this approach, lets see an example.

The example will be based on football. Let’s imagine that any football team can play in two manners: attacking and defending. These two tactics are particular realisations of a football strategy.

Strategy-Design-Pattern

Strategy interface:

public interface FootballStrategy {
	
	public void adhereTactic(String team);

}

Concrete realizations:

public class AttackTactic implements FootballStrategy {

	@Override
	public void adhereTactic(String team) {
		System.out.println(team+" will play in attacking football!");
	}

}

And

public class DefenceTactic implements FootballStrategy {

	@Override
	public void adhereTactic(String team) {
		System.out.println(team+" will make emphasis on defence!");
	}

}

Context class:

public class TacticContext {
	
	private FootballStrategy strategy = null;
	
	public void selectTactic(String team) {
		strategy.adhereTactic(team);
	}

	public FootballStrategy getStrategy() {
		return strategy;
	}

	public void setStrategy(FootballStrategy strategy) {
		this.strategy = strategy;
	}

}

Demonstration of the Strategy usage:

...
	public static void main(String[] args) {
		
		String team1 = "Barcelona";
		String team2 = "Real Madrid";
		
		TacticContext context = new TacticContext();
		
		context.setStrategy(new AttackTactic());
		context.selectTactic(team1);
		
		context.setStrategy(new DefenceTactic());
		context.selectTactic(team2);
		
	}
...

The result of the code execution:

Barcelona will play in attacking football!
Real Madrid will make emphasis on defence!

When to use the Strategy design pattern? Definitely when a client doesn’t need to know about implementation of concrete strategies or about data which is used there. When you want to use one class from the set dynamically. I don’t know which situations I also need to mention now. But I’m sure that my example was verbose and you can make your own conclusion about cons and pros of the Strategy design pattern.

Share and Enjoy

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS