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

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;
}
// 策略一: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");
}
}
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);
}
}
| 維度 | 策略模式 | 工廠模式 |
|---|---|---|
| 核心目的 | 封裝行為/演算法,支援執行期熱換拔 | 封裝物件建立,隱藏實例化細節 |
| 關注點 | 「怎麼做」 | 「建立什麼」 |
| 典型結構 | Context 持有 Strategy 介面參考 | Factory 介面 + 具體 Factory 子類 |
| 組合關係 | 常與工廠結合:工廠建立具體策略實例 | 可建立策略物件 |
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 結合函數式特性,讓策略模式的實作更加輕量直觀。