看了Jdon上寫的的策略模式,例子很簡單,代碼有些錯誤。http://www.jdon.com/designpatterns/ 文章寫的比較早,其實現在的策略模式大多是用Enum來實現,會簡單的多,但是思想不變:不同的演算法或者行為各自封裝,使用者自行挑選。
先摘抄他上面的代碼,錯誤已經改正:
Strategy策略模式是屬於設計模式中 對象行為型模式,主要是定義一系列的演算法,把這些演算法一個個封裝成單獨的類.Strategy應用比較廣泛,比如, 公司經營業務變化圖, 可能有兩種實現方式,一個是線條曲線,一個是框圖(bar),這是兩種演算法,可以使用Strategy實現.這裡以字串替代為例, 有一個檔案,我們需要讀取後,希望替代其中相應的變數,然後輸出.關於替代其中變數的方法可能有多種方法,這取決於使用者的要求,所以我們要準備幾套變數字元替代方案。
public abstract class RepTempRule { protected static String oldString= "aaa , bbb";protected String newString=""; public void setOldString(String oldString){ this.oldString=oldString;} public String getNewString(){ return this.newString ;} public abstract String replace() throws Exception; } public class RepTempRuleOne extends RepTempRule{ @Overridepublic String replace() throws Exception {// TODO Auto-generated method stubnewString=oldString.replaceFirst("aaa", "XXX");return newString ;} } public class RepTempRuleTwo extends RepTempRule{ @Overridepublic String replace() throws Exception {// TODO Auto-generated method stubnewString=oldString.replaceFirst("bbb", "***");return newString ;} } public class RepTempRuleSolve {private RepTempRule strategy; public RepTempRuleSolve(RepTempRule rule){ this.strategy=rule ;} public String getNewContext() {try {return strategy.replace();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}return null ;} public void changeAlgorithm(RepTempRule newAlgorithm) {strategy = newAlgorithm;}}public class Test { public static void main(String... agrs){ RepTempRuleSolve repTempRuleSolve=new RepTempRuleSolve(new RepTempRuleOne()); String newString=repTempRuleSolve.getNewContext(); System.out.println("Rule one :"+ newString); repTempRuleSolve.changeAlgorithm(new RepTempRuleTwo()); newString=repTempRuleSolve.getNewContext(); System.out.println("Change to Rule two :"+ newString); } }
我們達到了在運行期間,可以自由切換演算法的目的。
實際整個Strategy的核心部分就是抽象類別的使用,使用Strategy模式可以在使用者需要變化時,修改量很少,而且快速.
Strategy和Factory有一定的類似,Strategy相對簡單容易理解,並且可以在運行時刻自由切換。Factory重點是用來建立對象。
Strategy適合下列場合:
1.以不同的格式儲存檔案;
2.以不同的演算法壓縮檔;
3.以不同的演算法截獲圖象;
4.以不同的格式輸出同樣資料的圖形,比如曲線 或框圖bar等