Article directory
What is the strategy pattern
Strategy pattern is a behavioral design pattern. The purpose of any program is to solve a problem. In order to solve the problem, we need to write a specific algorithm, and the strategy mode can replace the algorithm as a whole.
example:
There are also examples of strategy patterns in java, such as functional interfaces and lambda expressions
Example: convert string case
StringPrintStragegy strategy interface
package BehavioralPattern.StrategyMode;
/**
* 字符串打印策略
*/
public interface StringPrintStragegy {
/**
* 字符串转换
*/
String changeString(String s);
}
ToLowerCaseStragegy string to lowercase strategy
package BehavioralPattern.StrategyMode;
/**
* 字符串转小写
*/
public class ToLowerCaseStragegy implements StringPrintStragegy{
@Override
public String changeString(String s) {
return s.toLowerCase();
}
}
ToUpperCaseStragegy string to uppercase strategy
package BehavioralPattern.StrategyMode;
/**
* 字符串转大写
*/
public class ToUpperCaseStragegy implements StringPrintStragegy{
@Override
public String changeString(String s) {
return s.toUpperCase();
}
}
StringChangeTool string conversion tool (use strategy)
package BehavioralPattern.StrategyMode;
/**
* 字符串转换工具
*/
public class StringChangeTool {
private StringPrintStragegy stragegy;
public StringChangeTool(StringPrintStragegy stragegy) {
this.stragegy = stragegy;
}
public String change(String s){
return stragegy.changeString(s);
}
}
Main
package BehavioralPattern.StrategyMode;
/**
* Main
*/
public class Main {
public static void main(String[] args) {
String s = "HelLo WoRld";
//使用策略
StringChangeTool lowerTool = new StringChangeTool(new ToLowerCaseStragegy());
StringChangeTool upperTool = new StringChangeTool(new ToUpperCaseStragegy());
System.out.println(lowerTool.change(s));
System.out.println(upperTool.change(s));
}
}
result
Summarize
The core idea of the strategy pattern is to extract the algorithm that is easy to change in a calculation method and pass it in as a "strategy" parameter, so that the new strategy does not need to modify the original logic. The strategy pattern is also a good replacement for if-else in code.
Different from template method mode:
template method mode --------- the whole process
strategy mode --------- a specific algorithm in the process