How to use Strategy Pattern in Java?
Hi everyone, you might have heard, “Can you tell me about any design pattern other than Singleton design pattern that you have used recently in your project?”. This is one of the popular questions in various Java interviews in recent years. I think this has actually motivated many Java programmers to explore more design patterns and actually look at the original 23 patterns introduced by GOF. Strategy design pattern is one of the useful patterns that we can mention while answering such questions. It is quite popular and there are many real-world scenarios where Strategy pattern comes very handy.
What is the best way to learn design patterns? First you need to understand how other people use them. To do this, you need to look at the open source libraries that we use in our daily tasks. JDK API is one such library that I use on a daily basis, that’s why when I explore new algorithms, design patterns, I first search JDK to understand their usage.
The Strategy pattern has found its place in JDK and if you have ever ArrayList
sorted a in Java, you will understand. Yes, the combination of Comparator, Comparable
and Collections.sort()
methods is one of the best real-life examples of Strategy design pattern.
To understand it more deeply, let's first understand what is the strategy pattern ? The first clue is the name itself. The strategy pattern defines a family of related algorithms, like sorting algorithms, such as bubble sort, quick sort, insertion sort, and merge sort, or compression algorithms, such as zip , gzip , tar , jar , encryption algorithms, such as MD5 , AES , etc., and makes the algorithm independent of the user who uses it.
For example, we can use the strategy pattern to implement a method to sort numbers and allow the client to choose any sorting algorithm at runtime without modifying the client's code. So essentially, the strategy pattern provides flexibility, extensibility, and choice. When we need to choose an algorithm at runtime, we should consider using this pattern.
In Java, strategies are usually Strategy
implemented by creating a hierarchy of classes that extend from a base interface called . In this tutorial, we will learn some interesting things about the Strategy pattern by writing a Java program and demonstrating how it can add value to our code.
The Ultimate Guide to Java Strategy Design Pattern
Now, let's dive deeper into the Strategy design pattern . I have covered what the Strategy design pattern is , the benefits it provides, where to use the Strategy pattern , and how to implement the Strategy design pattern in Java.
We will also see some real examples of the Strategy design pattern, especially from JDK and other popular open source libraries, to gain a deeper understanding of the intention of the Strategy design pattern. After reading this article, you should have the confidence to use the Strategy design pattern in your own Java projects and programs.
1. What is the intention of the Strategy design pattern?
When learning a new pattern, the most important thing is to understand the intent and motivation. Why? Because two design patterns can have the same structure, but their intent can be completely different. A good example of this theory is the State and Strategy pattern .
If you look at the diagram of both patterns UML
, they look the same, but the purpose of the State pattern is to facilitate state transitions, while the purpose of the Strategy pattern is to change the behavior of a class by changing the internal algorithm at runtime without modifying the behavior of the class. This is why the Strategy pattern is part of the Behavioral patterns in the original list of GOF.
We can relate the Strategy pattern to how people use different strategies to handle different situations, for example, if we encounter a situation then we either handle it or avoid it using two different strategies.
2. Terminology and structure of the strategy pattern
The pattern has two main components, Strategy
interfaces and Context
classes. Strategy
Interfaces declare the type of algorithm and can be either abstract classes or interfaces. For example, you can define an interface with a method move()
, Strategy
now this move becomes a strategy, and different pieces in a chess game can implement this method to define their move strategy.
例如
,Rook
can only move horizontally or vertically,Bishop
will move diagonally,Pawn
one square at a time, andQueen
can move horizontally, vertically, and diagonally. The different strategies used to move different pieces areStrategy
the implementation of the interface, and the code to move the pieces is ourContext
class.
When we change a piece, we don't need to change the context class. If a new fragment is added, then your code responsible for moving the fragments also does not need to be modified.
Here is the UML diagram for the Strategy pattern:

3. Advantages and disadvantages of strategy pattern
Every algorithm or pattern has advantages and disadvantages and this pattern is no exception. The main benefit of using the strategy pattern is flexibility. The client can choose any algorithm at runtime and we can easily add new strategies without modifying Context
the classes that use the strategy.
This is possible because the Strategy pattern is based on the open-closed design principle, which means that new behavior is added by writing new code rather than by modifying old, tried-and-true code.
如果我们使用策略模式,我们将通过编写一个只需要实现 Strategy
接口的新类来添加一个新的策略。 因为违反了开闭原则,我们不能用枚举来实现策略模式。
虽然它有一些优点并且很适合如果我们提前了解主要算法但我们需要修改 Enum 类以添加新算法,这违反了开闭原则。
4. 策略设计模式的真实例子
JDK 有几个这种模式的例子,第一个是 Collection.sort(List, Comparator)
方法,其中 Comparator
是 Strategy,Collections.sort()
是 Context。 由于这种模式,我们的排序方法可以对任何对象进行排序,该对象在编写此方法时不存在。
只要,Object 会实现 Comparator
接口(Strategy 接口),Collections.sort()
方法就会对其进行排序。
另一个例子是 java.util.Arrays#sort(T[], Comparator < ? super T > c)
方法,它类似于 Collections.sort()
方法,只是需要用数组代替 List。
5. Java中策略模式的实现
这是一个实现策略设计模式的简单 Java 程序。 我们可以使用此示例代码来学习和试验此模式。 这个例子非常简单,它所做的就是为排序算法定义一个策略接口,并在一个名为 arrange 的方法上使用该接口。
此方法可以按升序或降序排列对象,具体取决于我们如何实现它们。 为了安排一个对象,我们需要排序,这是由策略模式提供的。 这允许我们选择任何算法来对我们的对象进行排序。
public class Test {
public static void main(String args[]) throws InterruptedException {
// we can provide any strategy to do the sorting
int[] var = {1, 2, 3, 4, 5 };
Context ctx = new Context(new BubbleSort());
ctx.arrange(var);
// we can change the strategy without changing Context class
ctx = new Context(new QuickSort());
ctx.arrange(var);
}
}
interface Strategy {
public void sort(int[] numbers);
}
class BubbleSort implements Strategy {
@Override
public void sort(int[] numbers) {
System.out.println("sorting array using bubble sort strategy");
}
}
class InsertionSort implements Strategy {
@Override
public void sort(int[] numbers) {
System.out.println("sorting array using insertion sort strategy");
}
}
class QuickSort implements Strategy {
@Override
public void sort(int[] numbers) {
System.out.println("sorting array using quick sort strategy");
}
}
class MergeSort implements Strategy {
@Override
public void sort(int[] numbers) {
System.out.println("sorting array using merge sort strategy");
}
}
class Context {
private final Strategy strategy;
public Context(Strategy strategy) {
this.strategy = strategy;
}
public void arrange(int[] input) {
strategy.sort(input);
}
}
上述代码输出结果如下
sorting array using bubble sort strategy
sorting array using quick sort strategy
6. 关于 Java 中策略模式的注意事项
现在让我们复习一下在本篇文章中学到的有关策略模式的知识:
- 该模式定义了一组相关的算法并将它们封装在单独的类中,并允许客户端在运行时选择任何算法。
- 它允许在不修改现有算法或使用算法或策略的上下文类的情况下添加新算法。
- 策略是GOF列表中的一种行为模式。
- 策略模式基于SOLID Principles of Object-Oriented Design的开闭设计原则。
-
Collections.sort()
和 Comparator 接口是策略模式的真实示例。
这就是关于如何在 Java 中实现策略模式的全部内容。
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
Difference between Proxy Mode and State Mode in Java
Publish Date:2025/03/19 Views:74 Category:ALGORITHM
-
Hi guys, if you are preparing for Java interview and looking for difference between Proxy and State design pattern, then you are at the right place. In the past, I have explained several important object-oriented design patterns like State,
Strategy Design Pattern and Open-Closed Principle in Java
Publish Date:2025/03/19 Views:111 Category:ALGORITHM
-
The Strategy design pattern is based on the Open/Closed design principle , the famous " O SOLID " of design principles . It is one of the patterns that has become popular in the field of object-oriented analysis and design, along with the D
How to implement binary search in Java without recursion?
Publish Date:2025/03/19 Views:196 Category:ALGORITHM
-
Hey Java programmers, if you want to implement binary search in Java and looking for iterative and recursive binary search algorithms, then you have come to the right place. Today I am going to teach you an important algorithm. In computer
How to implement the singleton pattern in JavaScript ES6+
Publish Date:2025/03/19 Views:54 Category:ALGORITHM
-
In this article, we will show you how to implement the singleton pattern in JavaScript. If we are a full-stack JavaScript developer, we know that JavaScript is a powerful language and we can build amazing websites with it. On the other hand
How to use the Adapter design pattern in Java
Publish Date:2025/03/19 Views:76 Category:ALGORITHM
-
The Adapter design pattern in Java , also known as the Wrapper pattern, is another very useful GOF pattern that helps bridge the gap between two classes in Java. According to the Gang of Four pattern list, Adapter is a structural pattern, m
Java Decorator Design Pattern Example
Publish Date:2025/03/19 Views:115 Category:ALGORITHM
-
Hello everyone, if you want to learn about Decorator Design Pattern in Java , then you have come to the right place. As design patterns are very important while building software and equally important in any core Java interview, it is alway
How to implement the Command Design Pattern in Java
Publish Date:2025/03/19 Views:176 Category:ALGORITHM
-
Hello everyone, today, we will learn an important design pattern which is often overlooked by Java developers. Yes, I am talking about the Command pattern which helps us write flexible and loosely coupled code to implement actions and event
How to use the State Design Pattern in Java?
Publish Date:2025/03/19 Views:143 Category:ALGORITHM
-
The State design pattern is a behavioral pattern. The State pattern looks similar to the Strategy pattern, but it helps in managing the object states so that they behave differently in different states. In this example, we will take a famou
Adapter vs Decorator vs Facade vs Proxy Design Pattern in Java
Publish Date:2025/03/19 Views:67 Category:ALGORITHM
-
There are some striking similarities between the Adapter, Decorator, Facade, and Proxy design patterns as they all use composition and delegation to solve problems. The Adapter pattern wraps an interface and delegates calls to it. Decorator