
Java programmer expert
Today we will look at the last Java design pattern from the category of behavioural patterns – Strategy. Java design patterns in this category deal with the interaction between objects and their responsibility.
Strategy is a design pattern that allows you to dynamically change the behaviour of a class or its algorithms as needed at runtime. For example, if 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 just before it is used.
The Strategy pattern addresses the problem of having the flexibility to change the way a certain functionality is implemented in a program at runtime. It allows you to define a family of algorithms or strategies, put 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 behaviour 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.
This code demonstrates the use of the Strategy design pattern in the context of a hockey coach and his ability to switch between offensive and defensive strategies based on the current state of the game.
GameStrategy.java
package designpatterns;
public interface HernaStrategia {
void vykonat();
}
GameStrategy is an interface that defines how to implement a strategy. It contains a single execute() method that defines how the strategy is to be executed.
OffensiveStrategy.java, DefensiveStrategy.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.");
}
}
OffensiveStrategy and DefensiveStrategy are concrete implementations of the GameStrategy interface. Each of these classes implements the execute() method to execute a specific strategy – offensive 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 GameStrategy attribute that holds the current strategy. The changeStrategy() method is used to change the current strategy and the executeStrategy() 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 strategy instances – offensive and defensive. This is followed by a simulation of the match, where the strategies change as the match progresses.
The output of this example is:
The Strategy pattern is often used when we need to dynamically change the behaviour of a class or its strategies on the fly.
We have prepared the files with the above example as code that you can run directly in Java. You can 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!