首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 設計模式:策略模式實戰詳解

     編輯:Java 相關知識

模式定位

策略模式屬於物件行為型模式。核心思想:定義一系列演算法,將每個演算法封裝為獨立類別,使它們可以互換。讓演算法的變化獨立於使用演算法的客戶端。

經典應用場景

  • 檔案以不同格式儲存(XML、JSON、CSV、二進位)
  • 不同壓縮演算法(ZIP、GZIP、BZIP2、LZ4)
  • 圖形以不同方式輸出(曲線圖、長條圖、餅圖)
  • 字串替換/驗證/解析的多種規則
  • 路徑規劃:最短路徑、最少換乘、避開擁擠

結構圖解

策略模式類別圖

實戰案例:可換拔的字串範本替換引擎

1. 定義抽象策略基類


public abstract class RepTempRule {
    protected String oldString = "";
    protected String newString = "";

    public void setOldString(String oldString) { this.oldString = oldString; }
    public String getNewString() { return newString; }
    
    // 核心抽象方法:由具體策略實現
    public abstract void replace() throws Exception;
}

2. 實現具體策略


// 策略一:aaa → bbbb
public class RepTempRuleOne extends RepTempRule {
    @Override
    public void replace() throws Exception {
        // JDK 1.4+ replaceFirst 使用正則
        newString = oldString.replaceFirst("aaa", "bbbb");
        System.out.println("this is replace one");
    }
}

// 策略二:aaa → ccc
public class RepTempRuleTwo extends RepTempRule {
    @Override
    public void replace() throws Exception {
        newString = oldString.replaceFirst("aaa", "ccc");
        System.out.println("this is replace two");
    }
}

3. 客戶端動態切換策略


public class TemplateProcessor {
    public String process(String template, RepTempRule strategy) throws Exception {
        strategy.setOldString(template);
        strategy.replace();
        return strategy.getNewString();
    }
}

// 使用範例
public class Test {
    public void testReplace() throws Exception {
        String record = "用戶 aaa 歡迎光臨";
        
        // 依據業務規則動態選擇策略
        RepTempRule rule = new RepTempRuleOne(); // 或 new RepTempRuleTwo()
        TemplateProcessor processor = new TemplateProcessor();
        String result = processor.process(record, rule);
        System.out.println("替換結果:" + result);
    }
}

策略模式 vs 工廠模式

維度策略模式工廠模式
核心目的封裝行為/演算法,支援執行期熱換拔封裝物件建立,隱藏實例化細節
關注點「怎麼做」「建立什麼」
典型結構Context 持有 Strategy 介面參考Factory 介面 + 具體 Factory 子類
組合關係常與工廠結合:工廠建立具體策略實例可建立策略物件

進階應用技巧

策略註冊表(避免大量 if-else)


public class StrategyRegistry {
    private static final Map STRATEGIES = new HashMap<>();
    
    static {
        STRATEGIES.put("RULE_ONE", new RepTempRuleOne());
        STRATEGIES.put("RULE_TWO", new RepTempRuleTwo());
        // 可從配置檔/資料庫動態載入
    }
    
    public static RepTempRule getStrategy(String key) {
        return STRATEGIES.getOrDefault(key, new RepTempRuleOne()); // 預設策略
    }
}

// 使用
RepTempRule rule = StrategyRegistry.getStrategy(config.getRuleKey());

函數式介面簡化

Java 8+ 可用 Function<String, String> 或自訂 @FunctionalInterface 替代抽象類,配合 Lambda 表達式極度精簡:


@FunctionalInterface
interface StringReplacer {
    String replace(String input);
}

// 直接用 Lambda 定義策略
StringReplacer rule1 = s -> s.replaceFirst("aaa", "bbbb");
StringReplacer rule2 = s -> s.replaceFirst("aaa", "ccc");

總結

策略模式以「組合大於繼承」實現演算法的封裝、隔離與動態切換。它讓系統在面對「同一問題、多種解法」時保持優雅擴展,是消除條件判斷、實現開閉原則的利器。現代 Java 結合函數式特性,讓策略模式的實作更加輕量直觀。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved