Member-only story
Strategy Design Pattern With Spring Boot
Strategy Design Pattern
Strategy design pattern is a behavioral design pattern that enables selecting an algorithm at run-time.
The intent of the Strategy design pattern is to:
“Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.” [GoF]
UML class and sequence diagram from wiki

There are quite number of articles explaining Strategy design pattern and
how to implement them in various languages. The intent of this article is to
learn how to implement strategy pattern in a spring boot application.
Spring Boot
Spring Boot has become the de facto standard for Java microservice development. It is useful to learn how to implement common design patterns in spring boot applications.
Spring introduced the @Autowired annotation for dependency injection.
Any of the Spring components can be autowired. These include, components, configurations, services and beans.
In this article we will implement Strategy Design Pattern using dependency injection.
First we will start implementing family of algorithms need for Strategy Pattern. Here is the interface for the strategy algorithm with doStuff() ( for implementing the algorithm).
public interface Strategy { void doStuff(); StrategyName getStrategyName();}
and we identify each strategy using StrategyName defined as enum.
public enum StrategyName {
StrategyA,
StrategyB,
StrategyC
}
Here are the three algorithms for the Strategy pattern. Each of these algorithms are uniquely identified using StrategyName.
It is good to use enum rather than a String to identify the strategy.
StrategyA
@Component
public class StrategyA implements Strategy{ @Override
public void doStuff() {…