Strategy策略模式

定義

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)點

  • 算法可以自由切換;
  • 避免使用多重條件判斷;
  • 擴展性良好

缺點

  • 策略類會增多;
  • 所有策略類都需要對外暴露
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容