設計模式-行爲型之策略(strategy)模式

定義

  • 整體替換算法。

使用場景

  • 針對於不同的場景提供不同的解決方案(算法)。

UML圖

在這裏插入圖片描述

代碼實現

//策略接口
public interface Strategy {
    public void sort(Integer[] arr);
}
//升序(容我偷懶直接用Comparator 和 Arrays工具類實現)
public class AscStrategy implements Strategy {
    @Override
    public void sort(Integer[] arr) {
        Comparator<Integer> comparator = new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                if(o1 > o2){
                    return 1;
                }
                return -1;
            }
        };
		//其實Arrays的sort 方法就是一個典型的策略模式應用,傳入不同的排序策略
        Arrays.sort(arr,comparator);
    }
}
//降序
public class DescStrategy implements Strategy {
    @Override
    public void sort(Integer[] arr) {
        Comparator<Integer> comparator = new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
               if(o1<o2){
                   return 1;
               }
               return -1;
            }
        };
        Arrays.sort(arr,comparator);
    }
}
//使用者
public class ArrayUser {
    private Strategy strategy;

    public ArrayUser(Strategy strategy) {
        this.strategy = strategy;
    }

    //用於替換算法
    public void setStrategy(Strategy strategy) {
        this.strategy = strategy;
    }

    public void mySort(Integer[] arr){
        strategy.sort(arr);
    }
}
//測試
public class Client {
    public static void main(String[] args) {
        ArrayUser arrayUser = new ArrayUser(new AscStrategy());
        Integer[] arr = {9,4,7,5,8,2,3,1};
        arrayUser.mySort(arr);
        System.out.println(Arrays.toString(arr));
        arrayUser.setStrategy(new DescStrategy());
        arrayUser.mySort(arr);
        System.out.println(Arrays.toString(arr));
    }
}

總結

  • 用於替換整體算法。
  • 使用聚合的方式進行解耦,採用接口實現的方式進行實現(面向接口編程)。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章