Strategy Design Pattern in Java

In software engineering, a software design pattern is a general, reusable solution to a commonly occurring problem within a given context in software design. It is not a finished design that can be transformed directly into a source or machine code. Rather, it is a description or template for how to solve a problem that can be used in many different situations.

Design patterns are formalized best practices that the programmer can use to solve common problems when designing an application or system.

The strategy design pattern is a behavioral design pattern where we choose a specific implementation of tasks in run time from the multiple implementations for the same task.

Strategy pattern enables a client code to choose from a family of related but different algorithms and gives it a simple way to choose any of the algorithms in runtime depending on the client context.

The best example of the strategy pattern is the Collections.sort() method that takes the Comparator parameter. Based on the different implementations of Comparator interfaces, the Objects are getting sorted in different ways.

Example of strategy design pattern

1). Java Collections.sort(list, comparator) method where the client actually passes a suitable comparator based on the requirement in runtime to the method and the method is generic to accept any comparator type. Based on the comparator being passed, the same collection can be sorted differently.

2). Appenders, Layouts, and Filters in Log4j.

3). Layout Managers in UI toolkits.

Let use Strategy design pattern real-life example.

Reach to Office- Where we can reach the office by using different strategies like Carpool, Train, Bus, Auto, Bike. First, we'll need a strategy

public interface OfficeReachStrategy { public static final distance = 23; public void calculateFare(); } public class TrainTravelStrategy implements OfficeReachStrategy { private String name; private String number; private String time; private String trainClass; public TrainTravelStrategy(String name, String number, String time, String trainClass) { this.name = nm; this.number = number; this.time = time; this.trainClass = trainClass; }@Override public void calculateFare() { double fare = 0.0; if (trainClass.equls("second")) { float temp = TrainTravelStrategy.distance / 10; fare = temp * 2; } if (trainClass.equls("first")) { float temp = TrainTravelStrategy.distance / 10; fare = temp * 4.2; } System.out.println("The total fare required to travel by train is" + fare); } } public class CarPoolStrategy implements OfficeReachStrategy { private String name; private String number; private String type; private String arrivalTime; private float amountPerSeat; public CarPoolStrategy(String name, String number, String type, String arrivalTime, float amountPerSeat) { this.name = name; this.number = number; this.type = type; this.arrivalTime = arrivalTime; this.arrivalTime = amountPerSeat; } @Override public void calculateFare() { System.out.println("The total fare required to travel by CarPool is : " + amountPerSeat); } public class AutoTravelStrategy implements OfficeReachStrategy { private String name; private String number; private String chargePerKM; public AutoTravelStrategy(String name, String number, double chargePerKM) { this.name = name; this.number = number; this.chargePerKM = chargePerKM; } @Override public void calculateFare(int amountPerKM) { System.out.println("The total fare required to travel by Auto is : " + distance * amountPerKM); } public class OfficeReachStrategyTest { public static void main(String[] args) { OfficeReachStrategy autoStrategy = new AutoTravelStrategy("XYZ Auto", "MH-01 2345", 18.00); autoStrategy.calculateFare(); OfficeReachStrategy carPoolStrategy = new CarPoolStrategy("Ola Car Pool", "MH-43 4376", "SEDAN", "09:30am", 80.00) autoStrategy.calculateFare(); OfficeReachStrategy trainTraveStrategy = new TrainTravelStrategy("Panvel-CST", "674560", "09:40 am ", "first"); trainTraveStrategy.calculateFare(); } }

More about Strategy design pattern

"Strategy pattern is based upon the Open Closed design principle of SOLID principals."

The strategy is a behavioral pattern in the Gang of Four Design pattern list. 

 
"Defines a set of encapsulated algorithms that can be swapped to carry out a specific behavior"


It allows adding a new algorithm without modifying existing algorithms or context class, which uses algorithms or strategies.

Post/Questions related to the Strategy Design Pattern in Java

Where to Use the Strategy Design Pattern?

In this article, we have seen the Strategy Design Pattern in Java. All source code in the article can be found in the GitHub repository.