設計模式(二)——策略模式

策略模式


  • 介紹

    • 結構圖:
      在這裏插入圖片描述
      (自我總結)核心: 工廠類(判斷生成對象以及一系列以次對象爲基礎的getResult()方法)和頂層抽象類(用於管理一系列的實現類)
  • 優點:

    • 前臺(調用者):
      只需要知到Context的使用規則就好了,相比較簡單工廠連IStrategy的實際使用都不需要了解了
    • 開發者:
      可以根據需求在Context添加對象的方法組合(比如對象只有兩個數的相加,我們可以在Context內部對此方法連續調用,實現三個數的算法),自由添加新的算法(添加實現類)
  • 缺點:

    • 不夠滿足開閉-原則(可以避免調用者的修改代碼,但是在開發者和簡單工廠一樣需要維護if-else判斷列表)
    • Context的功能依賴內部的IStrategy,因此當Context一旦創建完成,功能就確定了。而簡單工廠,可以返回新的對象所以不會產生這種情況
  • 區別

    • 簡單工廠模式
    • 很多人會把策略模式和簡單工廠搞混,區別這兩者的最直接的方式就是,是否需要返回生成的對象
    • 簡單工廠更像是對象層次的處理,策略模式更像是方法層次的處理

  • 實例

實現一個計算器
通過輸入 + - ,對兩個整型數字進行運算 。

一、結構圖

在這裏插入圖片描述

通過圖我們明白,當我們把測錄模式創建之後,策略模式不像簡單工廠那樣,把產生的實際對象返回,而是在內部封裝使用。因此開發人員甚至只要知道Context的使用規則和API就可以了

二、代碼

// 模擬調用方 不屬於策略模式的主體
public class StrategyPatternMain {
    public static void main(String[] args) throws Exception {
        // 定義初始數據
        int num_a = 1;
        int num_b = 0;
        char char_opertion = '+';
        // 創建Context並獲取operation對象 隱藏了operation的創建過程
        // 用戶只需要知道createOperation以及getResut()的使用即可
        OperationContext operationContext = new OperationContext(char_opertion);
        // 使用對象得出結論
        int result = operationContext.getResult(num_a, num_b);
        System.out.println(result);
    }
}

// Operation應用上下文
public class OperationContext{
    // 注意了 這就是與普通的簡單工廠不一樣的地方,返回的對象保存在這
    private Operation operation;
    // 在實例化之處就解決了operation的使用
    public OperationContext(char oper) throws Exception {
    	// 這裏套用了簡單工廠的創建對象的方式
        switch (oper){
            case '+' :
                operation = new AddOperation();
            case  '-' :
                operation = new descOperation();
            default:
                    throw new Exception("該計算形式不合法");
        }
    }
    // 用戶調用API,調用者只會這個即可,不用知道Operation
    int getResult(int num_a, int num_b) throws Exception{
        if(operation != null){
            return operation.getResut(num_a, num_b);
        }else {
            throw new Exception("尚未添加策略選擇");
        }
    }
}

// Operation頂層抽象接口
public interface Operation {
	// 計算抽象接口
   int getResut(int num_a, int num_b);
}
// 加法計算器
public class AddOperation implements Operation {
    @Override
    public int getResut(int num_a, int num_b) {
        return num_a + num_a;
    }
}
// 減法計算器
public class descOperation implements Operation {
    @Override
    public int getResut(int num_a, int num_b) {
        return num_a - num_b;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章