define
The pattern defines a series of algorithms and encapsulates each algorithm so that they are interchangeable, and changes to the algorithm do not affect customers using the algorithm.
The class diagram
advantages
- The policy pattern provides perfect support for the open closed principle, allowing for the flexibility of adding new algorithms without modifying the original code.
- Multiple conditions can be avoided. Suppose A policy family has N members. If policy A is needed in one moment and policy B is needed in another moment, only ifelse or switch statements can be used without policy mode. However, such programs are not easy to maintain and have poor readability. Policy patterns can be determined by other modules.
disadvantages
- The client must understand the differences between all the policy algorithms in order to select the right algorithm class at the right time.
- The policy mode creates many policy classes, which increases the maintenance difficulty.
code
public class StrategyPattern {
public static void main(String[] args) {
Context c = new Context();
Strategy s = new ConcreteStrategyA();
c.setStrategy(s);
c.strategyMethod();
System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --");
s = newConcreteStrategyB(); c.setStrategy(s); c.strategyMethod(); }}// Abstract policy class
interface Strategy {
public void strategyMethod(); // strategy method
}
// Specific policy class A
class ConcreteStrategyA implements Strategy {
public void strategyMethod() {
System.out.println("The policy method of specific policy A is accessed!"); }}// Specific policy class B
class ConcreteStrategyB implements Strategy {
public void strategyMethod() {
System.out.println("The policy method for specific policy B is accessed!"); }}/ / environment
class Context {
private Strategy strategy;
public Strategy getStrategy() {
return strategy;
}
public void setStrategy(Strategy strategy) {
this.strategy = strategy;
}
public void strategyMethod(){ strategy.strategyMethod(); }}Copy the code
The running results of the program are as follows:
The policy method of specific policy A is accessed! ----------------- The policy method of specific policy B is accessed!Copy the code
Reference:
- Detailed explanation of the strategy pattern (strategy design pattern)