I learned about one of the design patterns, the Strategy pattern, so I will summarize it.
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 **.
--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.
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