[Java] Change the process according to the situation with the Strategy pattern

I learned about one of the design patterns, the Strategy pattern, so I will summarize it.

What is the Strategy pattern?

What is the Strategy pattern? GoF's [Design pattern](https://ja.wikipedia.org/wiki/%E3%83%87%E3%82%B6%E3%82%A4%E3%83%B3%E3% 83% 91% E3% 82% BF% E3% 83% BC% E3% 83% B3_ (% E3% 82% BD% E3% 83% 95% E3% 83% 88% E3% 82% A6% E3% 82 It is one of% A7% E3% 82% A2)).

Strategy stands for ** "strategy" **, The Strategy pattern is a design pattern for ** changing the behavior of an object according to the situation **.

Benefits of the Strategy pattern

--Separation of processing improves ease of maintenance --If you want to add a new strategy, just add a class that inherits the Strategy interface. --By encapsulating the process, the caller can use it without being aware of the specific process content.

Actually use

This time, using Pokemon Pikachu as an example, I will change the technique (strategy, behavior) according to the situation.

The Strategy pattern requires each strategy to have a ** common interface **.

Prepare the AttackStrategy interface below.

AttackStrategy.java


/**
*Attack interface
*/
public interface AttackStrategy {
    public void attack();
}

Then, prepare a class that implements the above interface for each strategy.

Override the method described in the interface and describe the actual processing.

This time, only standard output is used, but it is possible to describe more complicated processing.

ToGoodTypeConcreteStrategy.java


/**
*Strategy when the enemy is a good attribute
*/
public class ToGoodTypeConcreteStrategy implements AttackStrategy {

    @Override
    public void attack() {
        System.out.println("It's 100,000 volts!");
    }
}

ToBadTypeConcreteStrategy.java


/**
*Strategy when the enemy is not good at it
*/
public class ToBadTypeConcreteStrategy implements AttackStrategy {

    @Override
    public void attack() {
        System.out.println("It's a shadow alter ego!");
    }
}

Next, prepare a Pikachu class that has the variable _attackStrategy of the AttackStrategy interface prepared above as a field.

In the Pikachu class, define a constructor and setter for initializing _attackStrategy.

Also, define ʻattack () to call ʻAttackStrategy # attack (). (transfer)

This is the point of the Strategy pattern, and even though only ʻattack ()` is defined in the PikachuContex class, the actual processing content can be changed according to the situation.

PikachuContext.java


public class PikachuContext {
    private AttackStrategy _attackStrategy;

    public Pikachu(AttackStrategy strategy) {
        setStrategy(strategy);
    }

    public void attack() {
        _attackStrategy.attack();
    }
}

That's all for preparation. I will actually use it.

Main.java


public class Main {

    public static void main(String[] args) {

        PikachuContext pikachu;

        //When the enemy is a good attribute
        pikachu= new PikachuContext(new ToGoodTypeConcreteStrategy());
        pikachu.attack(); // "It's 100,000 volts!"Is output

        //If the enemy is not good at it
        pikachu = new PikachuContext(new ToBadTypeConcreteStrategy());
        pikachu.attack(); // "It's a shadow alter ego!"Is output
    }
}

Recommended Posts

[Java] Change the process according to the situation with the Strategy pattern
Memo: [Java] Process the read csv (extract, change according to the conditions) and output
Replace with a value according to the match with a Java regular expression
[Java] Strategy pattern
[Java] Explanation of Strategy pattern (with sample code)
Change seats with java
How to change the action with multiple submit buttons
HTTPS connection with Java to the self-signed certificate server
Java to play with Function
Change the port with SpringBoot
Shell to kill Java process
Enum Strategy pattern in Java
Connect to DB with Java
Connect to MySQL 8 with Java
[Java] Dealing with the situation where the program that writes to the Output Stream of Process does not end even if waitFor
Be sure to compare the result of Java compareTo with 0
How to change the file name with Xcode (Refactor Rename)
Input to the Java console
Returning to the beginning, getting started with Java ② Control statements, loop statements
I want to return to the previous screen with kotlin and java!
[Rails] How to introduce kaminari with Slim and change the design
If you want to change the Java development environment from Eclipse
Connecting to a database with Java (Part 1) Maybe the basic method
Design patterns to enjoy with frequently used Java libraries --Factory pattern
Process the motion detected by the motion sensor HC-SR501 with Raspberry Pi 3 & Java
[Java] I want to perform distinct with the key in the object
Java to learn with ramen [Part 1]
[java8] To understand the Stream API
[Java] Points to note with Arrays.asList ()
Dare to challenge Kaggle with Java (1)
[Java] Input to stdin of Process
I tried to interact with Java
Follow the link with Selenium (Java)
Welcome to the Java Library Swamp! !!
The road from JavaScript to Java
Java, arrays to start with beginners
A story that I wanted to write a process equivalent to a while statement with the Stream API of Java8
[swift5] How to change the color of TabBar or the color of item of TabBar with code
I tried to make a program that searches for the target class from the process that is overloaded with Java
[Java] How to use the File class
How to compile Java with VsCode & Ant
Java reference to understand in the figure
Introduction to java for the first time # 2
[Java] How to use the hasNext function
[Java] How to compare with equals method
Java SE8 Silver ~ The Road to Pass ~
[Java] How to use the HashMap class
About the procedure for java to work
Introduction to algorithms with java --Search (depth-first search)
[Java] How to use the toString () method
Studying how to use the constructor (java)
[Processing × Java] How to use the loop
Change the layout when rotating with onConfigurationChanged
Change List <Optional <T >> to Optional <List <T >> in Java
[Java] How to set the Date time to 00:00:00
[Java] How to get the current directory
How to change the timezone on Ubuntu
I tried to implement the Iterator pattern
Ransack sort_link How to change the color!
[Processing × Java] How to use the class
How to install the legacy version [Java]