Core Java

Design Patterns: Strategy

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 interface:

public interface FootballStrategy {

	public void adhereTactic(String team);


Concrete realizations:

public class AttackTactic implements FootballStrategy {

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



public class DefenceTactic implements FootballStrategy {

	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) {

	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.setStrategy(new DefenceTactic());


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.

Reference: Design Patterns: Strategy from our JCG partner Alexey Zvolinskiy at the Fruzenshtein’s notes blog.

Alexey Zvolinskiy

Alexey is a test developer with solid experience in automation of web-applications using Java, TestNG and Selenium. He is so much into QA that even after work he provides training courses for junior QA engineers.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button