Java design pattern: Strategy

Today we will look at the last Java design pattern from the category of behavioral patterns – Strategy . Design patterns in this category deal with the communication (interaction) between objects and their responsibility.

What is a Design Pattern Strategy?

Strategy is a design pattern that allows you to change the behavior of a class, or its algorithms dynamically as needed at runtime. If, for example. we have a class that performs data validation, the structure of the data may not be known before execution, and the validation algorithm to be used is decided immediately before it is used.

What problem does the Strategy design pattern solve?

The Strategy pattern addresses the problem of needing to flexibly change the way a certain functionality is implemented at runtime in a program. It allows you to define a family of algorithms or strategies, place each of them in a separate class, and ensure that their objects are interchangeable.

The main goal is to provide the ability to dynamically change the behavior of the object according to the chosen strategy. A context object is used to switch strategies, which has a reference to the strategy object and can also call its methods.

Example of Strategy implementation in Java

This code demonstrates the use of the Strategy design pattern in the context of a hockey coach and his ability to change the game between offensive and defensive strategies based on the current state of the game.

HernaStrategia.java

package designpatterns;

public interface HernaStrategia {
    void vykonat();
}

HernaStrategia is an interface that defines how a strategy can be implemented. It contains a single vykonat() method that defines how to execute the strategy.

UtocnaStrategia.java, ObrannaStrategia.java

package designpatterns;

public class UtocnaStrategia implements HernaStrategia {
    @Override
    public void vykonat() {
        System.out.println("Tím hrá v útočnej formácii.");
    }
}

public class ObrannaStrategia implements HernaStrategia {
    @Override
    public void vykonat() {
        System.out.println("Tím prechádza do obrannej formácie.");
    }
}

UtocnaStrategia and ObrannaStrategia are concrete implementations of the HernaStrategia interface. Each of these classes implements the vykonat() method to execute a specific strategy – attack or defensive.

Coach.java

package designpatterns;

// Kontext
public class Coach {
    private HernaStrategia hernaStrategia;

    public void zmenitStrategiu(HernaStrategia novaStrategia) {
        this.hernaStrategia = novaStrategia;
    }

    public void vykonatStrategiu() {
        hernaStrategia.vykonat();
    }
}

A coach is a context that uses a strategy. It has a hernaStrategia attribute that holds the current strategy. The zmenitStrategiu() method is used to change the current strategy and the vykonatStrategiu() method executes it.

Main.java

import designpatterns.Coach;
import designpatterns.HernaStrategia;
import designpatterns.ObrannaStrategia;
import designpatterns.UtocnaStrategia;

public class Main {
    public static void main(String[] args) {
        Coach coach = new Coach();
        HernaStrategia utocnaStrategia = new UtocnaStrategia();
        HernaStrategia obrannaStrategia = new ObrannaStrategia();

        System.out.println("Začala sa hra.");

        // Coach vyberá stratégiu podľa priebehu hry
        // Začíname s útočnou stratégiou
        coach.zmenitStrategiu(utocnaStrategia);
        coach.vykonatStrategiu();

        System.out.println("Tím striela gól a vedie.");

        // Ak tím vyhráva, zmeníme na obrannú stratégiu
        // (simulujeme, že sa tím dostáva do obrannej fázy, keď vedie v zápase)
        coach.zmenitStrategiu(obrannaStrategia);
        coach.vykonatStrategiu();

        System.out.println("Súper striela gól a vyrovnáva.");

        // Ak tím prehráva, môžeme sa opäť vrátiť k útočnej stratégii
        // (simulujeme, že tím znova prechádza do útočnej fázy, keď prehráva)
        coach.zmenitStrategiu(utocnaStrategia);
        coach.vykonatStrategiu();
    }
}

The Main class creates a Coach instance and two instances of strategies – offensive and defensive. This is followed by a simulation of the game, where strategies change according to the course of the match.

The output of this example is:

Output from the Java Design Pattern Strategy program.
The output of the example for the Strategy design pattern.

Summary

The Strategy pattern is often used when we need to change the behaviour of a class or a class. its strategies dynamically as needed on the fly.

We have prepared the files with the above example in the form of code that you can run directly in Java. Download the Java Strategy code here.

If you’re looking for a job and you’re a Java developer, check out our employee benefits and respond to our job offers.

About the author

Jozef Wagner

Java Developer Senior

Viac ako 10 rokov programujem v Jave, momentálne pracujem v msg life Slovakia ako Java programátor senior a pomáham zákazníkom implementovať ich požiadavky do poistného softvéru Life Factory. Vo voľnom čase si rád oddýchnem v lese, prípadne si zahrám nejakú dobrú počítačovú hru.

Let us know about you