[Java] Explanation of Strategy pattern (with sample code)

What is the Strategy pattern?

One of GoF's design patterns, which is a behavioral design pattern.

If you want to change the process while the program is running, you can easily switch the algorithm on the client side by using the Startegy pattern.

Why use the Strategy pattern

By using the Strategy pattern, the client side can easily switch algorithms, which reduces the burden on the client side.

It also has the advantage of improving readability and ease of maintenance because the code itself is clean.

If you are programming normally, you tend to use conditional branching in if statements when switching processes. However, if the processing content becomes complicated and the number of conditional branches increases, it becomes difficult to grasp the corrected part and determine the range of influence during repair work, and it becomes easy to lead to a bug.

When to use it

It is used when it is necessary to switch the algorithm.

For example, it is effective when you want to change the difficulty level of the game from Easy to Hard, or when you want to change the processing depending on the gender.

Sample code

Let's implement one simple process using the Strategy pattern.

Processing content

Consider the process of judging the entrance evaluation of each university based on the score of the university entrance examination.

Four people, "Kenta Suzumoto, Aya Yoshimura, Naoya Fukunaga, and Mai Masuoka," took the entrance examination. The scores for each are shown in the table below.

Name Score (out of 100)
Kenta Suzumoto 90 points
Aya Yoshimura 80 points
Naoya Fukunaga 70 points
Mai Masuoka 60 points

Suppose these four people receive three grades: high difficulty college, average college, and low college. Let's see what kind of evaluation each will receive while switching with the Strategy pattern.

Code details

First, create a class to evaluate the score at the university. In this class, the process of calling the Strategy class and evaluating is described without directly describing the evaluation method.

SampleClass.java



public class SampleClass {
  BaseStrategy currentStrategy;

  /*
  *SampleClass constructor
  * @param firstStrategy Strategy to set
  */
  public SampleClass(BaseStrategy firstStrategy) {
    this.currentStrategy = firstStrategy;
  }

  /*
  *changeStrategy Change Strategy
  * @param newStrategy Strategy to change
  */
  public void changeStrategy(BaseStrategy newStrategy) {
    this.currentStrategy = newStrategy;
  }

  /*
  *getOpinion Get an evaluation
  * @param pointMap Test score
  */
  public void getOpinion(Map<String, Integer> pointMap) {
    //Loop for the number of people in the class
    for (String name : pointMap.keySet()) {
      //Calculate evaluation result
      int result = currentStrategy.scoringTest(pointMap.get(name));

      //Output evaluation result
      if (result > 0) {
        System.out.println(name + "Mr .: Good evaluation");
      } else if (result == 0) {
        System.out.println(name + "Mr .: It is a normal evaluation");
      } else {
        System.out.println(name + "Mr .: It's a bad evaluation");
      }
    }
  }
}

Next, create an interface for the Strategy class. This is to unify the method name in each Strategy class.

This time, only the scoringTest method, which is responsible for calculating the evaluation, is implemented. The evaluation result of the return value is 1 for a good evaluation, 0 for a normal evaluation, and -1 for a bad evaluation.

BaseStrategy.java


public interface BaseStrategy {
  /*
  *scoringTest Calculate the evaluation
  * @parame point Test score
  * @return Good evaluation: 1,Normal evaluation: 0,Bad evaluation:-1
  */
  int scoringTest(int point);
}

Next, we will create an evaluation method at each university by inheriting BaseStrategy.java.

How to evaluate EasyUniversityStrategy 80 points or more is a good evaluation, 60 points or more is a normal evaluation, and 59 points or less is a bad evaluation.

EasyUniversityStrategy.java


public class EasyUniversityStrategy implements BaseStrategy {
  public int scoringTest(int point) {
    //If it is 80 points or more, it is a good evaluation
    if (point >= 80) {
      return 1;
    //If it is 60 points or more, it is a normal evaluation
    } else if (point >= 60) {
      return 0;
    //Bad evaluation if 59 points or less
    } else {
      return -1;
    }
  }
}

How to evaluate UsualUniverSityStrategy A good evaluation is 85 points or more, a normal evaluation is 70 points or more, and a bad evaluation is 69 points or less.

UsualUniverSityStrategy.java


public class UsualUniverSityStrategy implements BaseStrategy {
  public int scoringTest(int point) {
    //If it is 85 points or more, it is a good evaluation
    if (point >= 85) {
      return 1;
    //If it is 70 points or more, it is a normal evaluation
    } else if (point >= 70) {
      return 0;
    //Bad evaluation if 69 points or less
    } else {
      return -1;
    }
  }
}

How to evaluate HardUniverSityStrategy A good evaluation is 95 points or more, a normal evaluation is 80 points or more, and a bad evaluation is 79 points or less.

HardUniverSityStrategy.java


public class HardUniverSityStrategy implements BaseStrategy {
  public int scoringTest(int point) {
    //If it is 95 points or more, it is a good evaluation
    if (point >= 95) {
      return 1;
    //If it is 80 points or more, it is a normal evaluation
    } else if (point >= 80) {
      return 0;
    //Bad evaluation if 79 points or less
    } else {
      return -1;
    }
  }
}

Finally, in the main class, we will implement the process of evaluating the scores of 4 people by the evaluation method of each university.

SampleMain.java


public class SampleMain {
  public static void main(String args[]) {

    Map<String, Integer> pointMap = new HashMap<String, Integer>() {
      {
        put("Kenta Suzumoto", 90);
        put("Aya Yoshimura", 80);
        put("Naoya Fukunaga", 70);
        put("Mai Masuoka", 60);
      }
    };

    //Evaluated by EasyUniversityStrategy
    SampleClass sampleClass = new SampleClass(new EasyUniversityStrategy());
    System.out.println("Evaluation result of EasyUniversityStrategy");
    sampleClass.getOpinion(pointMap);

    //Evaluated by UsualUniverSityStrategy
    sampleClass.changeStrategy(new UsualUniverSityStrategy());
    System.out.println("Evaluated by UsualUniverSityStrategy");
    sampleClass.getOpinion(pointMap);

    //Evaluated by HardUniverSityStrategy
    sampleClass.changeStrategy(new HardUniverSityStrategy());
    System.out.println("Evaluated by HardUniverSityStrategy");
    sampleClass.getOpinion(pointMap);
  }
}

Execution result

Evaluation result of EasyUniversityStrategy Mai Masuoka: It's a normal evaluation Kenta Suzumoto: Good evaluation Naoya Fukunaga: Normal evaluation Aya Yoshimura: Good evaluation

Evaluated by UsualUniverSityStrategy Mai Masuoka: It's a bad evaluation. Kenta Suzumoto: Good evaluation Naoya Fukunaga: Normal evaluation Aya Yoshimura: It's a normal evaluation

Evaluated by HardUniverSityStrategy Mai Masuoka: It's a bad evaluation. Kenta Suzumoto: Normal evaluation Naoya Fukunaga: Bad evaluation Aya Yoshimura: It's a normal evaluation

Finally

I explained the Strategy pattern.

Even if you look at the sample code, you can see that the code is easier to understand than the conditional branching in the if statement. (I used to list conditional branches with if statements before ...)

It may be a little troublesome when considering class design etc., but considering the maintainability etc. later, the code will be cleaner if you use the Strategy pattern, so if there is an algorithm branch, please try using the Strategy pattern. !!

Recommended Posts

[Java] Explanation of Strategy pattern (with sample code)
[Java] Strategy pattern
Java sample code 02
Java sample code 03
Java sample code 04
Java sample code 01
Digital signature sample code (JAVA)
Java parallelization code sample collection
Enum Strategy pattern in Java
[Java] Change the process according to the situation with the Strategy pattern
Sample code to parse date and time with Java SimpleDateFormat
Think of a Java update strategy
Code Java from Emacs with Eclim
Java 9 new features and sample code
Java build with mac vs code
Execute packaged Java code with commands
EXCEL file update sample with JAVA
Sample code using Minio from Java
Basic structure of Java source code
Sample of using Salesforce's Bulk API from Java client with PK-chunking
[With sample code] Basics of Spring JDBC to learn with Blog app
Prepare Java development environment with VS Code
A record of setting up a Java development environment with Visual Studio Code
Link Java and C ++ code with SWIG
Strategy pattern
Explanation of Puzzle & Quest with Love Live
Sample code collection for Azure Java development
Strategy Pattern
[JaCoCo (Java Code Coverage)] Use with NetBeans
Minimum configuration sample to automatically release Lambda by Java with Code pipeline
Generate source code from JAR file with JD-GUI of Java Decompiler project
Execute Java code from cpp with cocos2dx
Try remote debugging of Java with Remote Containers in Visual Studio Code Insiders
Sample source code for finding the least common multiple of multiple values in Java
[Code] Forcibly breaks through the C problem "* 3 or / 2" of [AtCoder Problem-ABC100] with Java [Code]
Sample code to get the values of major SQL types in Java + MySQL 8.0
Static code analysis with Checkstyle in Java + Gradle
Test Data Builder pattern ~ Improve maintainability of test code
Make Java code coverage more comfortable with Jacoco 0.8.0
Calculate the similarity score of strings with JAVA
Using Gradle with VS Code, build Java → run
Java Repository of Eclipse with Maven: Missing artifact ~
Try debugging a Java program with VS Code
Profile-derived automation of Code Artifact authentication with Gradle
Build a Java development environment with VS Code
Script Java code
Java code TIPS
Java design pattern
[Java] Generics sample
java callback pattern
Design pattern ~ Strategy ~
Selenium sample (Java)
[Java] Singleton pattern
Java GUI sample
The procedure I did when I prepared the environment of gradle + Java with VS Code (Windows 10)
[Java] Adapter pattern
Java character code
[Java] Overview of Java
Java pattern memo
[Java] Sort ArrayList with elements of your own class
Build Java development environment with VS Code on Mac