策略模式

多种可选

场景


接口固定,运行时可替换细节行为

代码


Sample
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public interface Strategy {
void do();
}

public class StrategyA implements Strategy{
void do() {
//
}
}

public class Work {
public void do(Strategy s) {
s.do();
}
}

优缺点


  • 扩展性良好
  • 自由替换

应用


java.util.Collections#sort() 传入比较策略Comparator
java.util.concurrent.ThreadPoolExecutor构造/set传入RejectedExecutionHandler