Java implements Strategy pattern
Strategy pattern is a behavioral design pattern that allows the algorithm to be changed independently of the client using it. This pattern defines a series of algorithm classes and encapsulates each algorithm into a class, allowing them to replace each other, allowing the client to dynamically select the desired algorithm.
Applicable scenario: When a system needs to select one of several algorithms to execute, and these algorithms have a common behavioral interface, Strategy pattern can be considered. It can isolate algorithm changes from the clients using the algorithm, facilitating the addition, replacement, or deletion of policies without affecting the clients.
The benefits of this design pattern are as follows:
By encapsulating the changing parts, the algorithm is decoupled from the client, improving the flexibility and maintainability of the code.
2. The expansion and changes of the algorithm will not affect the client, just add a specific policy class.
3. The Strategy pattern transfers the selection of algorithms from the client to the environment class, which makes the selection of algorithms more flexible and can be dynamically changed at runtime.
Here is a simple Java code example:
Firstly, define a policy interface that includes the algorithms that need to be replaced:
public interface Strategy {
public void execute();
}
Then, implement specific policy classes, each of which encapsulates specific algorithms:
public class ConcreteStrategy1 implements Strategy {
public void execute() {
System.out.println("Executing Strategy 1");
}
}
public class ConcreteStrategy2 implements Strategy {
public void execute() {
System.out.println("Executing Strategy 2");
}
}
Next, create an environment class to maintain policy objects and select policies on the client as needed:
public class Context {
private Strategy strategy;
public Context(Strategy strategy) {
this.strategy = strategy;
}
public void executeStrategy() {
strategy.execute();
}
}
Finally, use the Strategy pattern in the client code:
public class Main {
public static void main(String[] args) {
Strategy strategy1 = new ConcreteStrategy1();
Context context1 = new Context(strategy1);
context1.executeStrategy();
Strategy strategy2 = new ConcreteStrategy2();
Context context2 = new Context(strategy2);
context2.executeStrategy();
}
}
In this way, according to different choices, the client can flexibly choose and switch different strategies without modifying the original code.