策略模式屬於物件行為型模式,做法是把一系列演算法各自封裝成獨立的類,讓它們可以在執行期自由替換。
它的應用面很廣。例如公司經營業務的變化圖,畫成折線圖或長條圖是兩種不同演算法,用策略模式就能讓使用者隨意切換;再比如同一份資料要輸出成不同格式,也是策略模式的典型場景。
下面以「字串替換」為例:讀入一份文件,把其中的變數佔位符替換掉再輸出。替換規則取決於使用者需求,因此我們準備幾套方案。
public abstract class RepTempRule {
protected String oldString = "";
public void setOldString(String oldString) {
this.oldString = oldString;
}
protected String newString = "";
public String getNewString() {
return newString;
}
public abstract void replace() throws Exception;
}
其中 replace() 是抽象方法,具體的替換邏輯由子類給出。
方案一:把 aaa 換成 bbbb。方案二:把 aaa 換成 ccc。
public class RepTempRuleOne extends RepTempRule {
public void replace() throws Exception {
// replaceFirst 是 jdk1.4 新增的特性
newString = oldString.replaceFirst("aaa", "bbbb");
System.out.println("this is replace one");
}
}
public class RepTempRuleTwo extends RepTempRule {
public void replace() throws Exception {
newString = oldString.replaceFirst("aaa", "ccc");
System.out.println("this is replace two");
}
}
public class RepTempRuleSolve {
private RepTempRule strategy;
public RepTempRuleSolve(RepTempRule rule) {
this.strategy = rule;
}
public String getNewContext(Site site, String oldString) {
return strategy.replace(site, oldString);
}
public void changeAlgorithm(RepTempRule newAlgorithm) {
strategy = newAlgorithm;
}
}
public class test {
public void testReplace() {
// 使用第一套替換方案
RepTempRuleSolve solver = new RepTempRuleSolve(new RepTempRuleOne());
solver.getNewContext(site, context);
// 換成第二套
solver = new RepTempRuleSolve(new RepTempRuleTwo());
solver.getNewContext(site, context);
}
}
如此一來,我們達到了在執行期自由切換演算法的目的。
整個策略模式的核心其實就是抽象類(或介面)的使用。需求變化時改動極小,切換成本幾乎為零。
策略與工廠有些相似,但策略更簡單直觀,而且支援執行期切換;工廠的重點則在於「建立物件」。策略模式適合的典型場合包括:以不同格式存档;以不同演算法壓縮檔案;以不同演算法擷取圖像;以及把同一份資料輸出成不同圖形,例如折線圖或長條圖。