This article summarizes Strategy. According to wikipedia, "Algorithms can be changed in various ways while being independent of the user." Reference: Strategy pattern
** Main characters **
NO | name | role |
---|---|---|
1 | context | Instantiate a strategy |
2 | Strategy | Algorithm interface |
3 | Concrete class of strategy | Algorithm implementation |
It is said that the algorithm is independent of the user, but the processing groups that can be replaced are hidden by the interface and summarized in detail. Localize the range of influence by replacing it if necessary.
** Implement the pattern ** We will implement it assuming that you will use the automatic ticket gate at the station. The Strategy pattern implements the act of passing through three types of ticket gates: "contactless IC card (Suica, ICOCA, etc.) ticket gates," "transfer ticket gates," and "ticket ticket gates."
** Strategy **
Strategy.java
interface Strategy {
void pass();
}
** Concrete class of strategy **
ConcreteNonContactTurnstile.java
class ConcreteNonContactTurnstile implements Strategy {
public void pass() {
System.out.println("Set And Touch!");
}
}
ConcreteTicketTurnstile.java
class ConcreteTicketTurnstile implements Strategy {
public void pass() {
System.out.println("Ticket accept");
}
}
ConcreteTransferTurnstile.java
class ConcreteTransferTurnstile implements Strategy {
public void pass() {
System.out.println("Transfer Line!");
}
}
context
ContextStation.java
class ContextStation {
Strategy strategy;
public ContextStation(Strategy strategy) {
this.strategy = strategy;
}
public void pass() {
strategy.pass();
}
}
** Execution class **
Main.java
class Main {
public static void main(String[] args) {
ContextStation contextStation;
contextStation = new ContextStation(new ConcreteNonContactTurnstile());
contextStation.pass();
}
}
result
Set And Touch!
As mentioned above, we abstract similar processing groups by implementing one interface. We are instantiating the following classes in the strategy via a class in the role of context that holds a reference to that interface. At the time of implementation, the purpose of this pattern is to change the processing content at high speed by replacing the XX part of the main class "new ContextStation (new Concrete XX)". If you want to add a new type of ticket gate "manned ticket gate", you can implement it by adding a concrete class of a new strategy and replacing the part of the pattern mentioned above.
Recommended Posts