Strategy模式是定义一系列算法,把这些算法定义成一个新的类,在运行的时候动态选择需要的算法。
策略模式的ULM图:
策略模式的例子如下
策略模式的例子如下:
//文本替换策略
abstract class TextStrategy {
protected String text;
public TextStrategy(String text) {
this.text = text;
}
public abstract String replace();
}
//替换算法1:将文本中"@r@n"替换为"@n"
class StrategyOne extends TextStrategy {
public StrategyOne(String text) {
super(text);
}
public String replace() {
System.out.println(“StrategyOne:”);
String result = text.replaceAll("@r@n", "@n"));
return result;
}
}
//替换算法2:将文本中"@n"替换为"@r@n"
class StrategyTwo extends TextStrategy {
public StrategyTwo(String text) {
super(text);
}
public String replace() {
System.out.println(“StrategyTwo:”);
String result = text.replaceAll(“@n", "@r@n"));
return result;
}
}
public class TextCharChange {
public static void replace(TextStrategy strategy) {
strategy.replace();
}
public static void main(String[] args){
String testText1 = "This is a test text!!@n Oh! Line Return!!@n";
String testText2 = This is a test text!!@r@n Oh! Line Return@r@n";
TextCharChange.replace(new StrategyOne(testText2));
TextCharChange.replace(new StrategyTwo(testText1));
}
}
State模式和Strategy模式很类似,但是又有很明显的区别:
1 State模式设定状态的变化,根据状态的变化来返回相应的处理。
2 Strategy模式是根据需求和场景选择适合的算法。
JDK中策略模式的应用:
•
java.util.concurrent.ThreadPoolExecutor.AbortPolicy
•
java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy
•
java.util.concurrent.ThreadPoolExecutor.DiscardOldestPolicy
•
java.util.concurrent.ThreadPoolExecutor.DiscardPolicy
•
java.util.Comparator