設計模式之Strategy(策略模式系列1)

來源:互聯網
上載者:User

看了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等

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.