定義
Strategy design pattern is one of the Gang of Four (GOF) design patterns. Strategy design pattern defines a set of encapsulated algorithms that can be swapped to carry out a specific behavior
一個功能,替換不同的實現(xiàn)方法;
功能 1.....N 實現(xiàn)方法
類圖

image.png
- Context: 用來操作策略的接口;
- Strategy: 策略接口
- ConcreteStrategy: 具體的策略;可進(jìn)行替換的就是這部分內(nèi)容
- Tip:策略的實現(xiàn)是一種多態(tài)的應(yīng)用,掌握多態(tài)是實現(xiàn)設(shè)計模式的關(guān)鍵。
適用場景
一個功能需要提供不同的實現(xiàn)方法的時候;
比如java中的compare可以寫一個自己的實現(xiàn),來替換原有的compare;Person可以使用age來比較,也可以使用weight來進(jìn)行比較;
Java中的Comparator
import java.util.ArrayList;
import java.util.List;
/**
* <p>
* description
* </P>
*
* @author: zhangss
* @since: 2020-07-01
**/
public class Person {
public int age;
public int weight;
private Person(int age, int weight){
this.age = age;
this.weight = weight;
}
@Override
public String toString() {
return "age: " + age + " weight: " + weight;
}
public static void main(String[] args) {
List<Person> personList = new ArrayList<>();
personList.add(new Person(16, 120));
personList.add(new Person(11, 54));
personList.add(new Person(30, 100));
System.out.println(personList);
personList.sort((o1, o2)->{
if(o1.age > o2.age){
return 1;
}
return -1;
});
System.out.println("sort by age: " + personList);
personList.sort((o1, o2)->{
if(o1.weight > o2.weight){
return 1;
}
return -1;
});
System.out.println("sort by weight: " + personList);
}
}
// 運行結(jié)果
[age: 16 weight: 120, age: 11 weight: 54, age: 30 weight: 100]
sort by age: [age: 11 weight: 54, age: 16 weight: 120, age: 30 weight: 100]
sort by weight: [age: 11 weight: 54, age: 30 weight: 100, age: 16 weight: 120]
ThreadPool 拒絕策略
java提供了4種默認(rèn)的拒絕策略,當(dāng)我們需要實現(xiàn)自己的拒絕策略時,實現(xiàn)RejectedExecutionHandler口中的rejectedExecution方法。將線程池的拒絕策略設(shè)置為自己的拒絕策略即可。
/**
* A handler for tasks that cannot be executed by a {@link ThreadPoolExecutor}.
*
* @since 1.5
* @author Doug Lea
*/
public interface RejectedExecutionHandler {
void rejectedExecution(Runnable r, ThreadPoolExecutor executor);
}
public class MyRejectedPolicy implements RejectedExecutionHandler {
@Override
void rejectedExecution(Runnable r, ThreadPoolExecutor executor){
// 具體的拒絕策略
}
}
// 設(shè)置拒絕策略
executor.setRejectedExecutionHandler(new MyRejectedPolicy());
優(yōu)點
- 算法可以自由切換;
- 避免使用多重條件判斷;
- 擴展性良好
缺點
- 策略類會增多;
- 所有策略類都需要對外暴露