設計模式學習筆記(一) 策略模式




 
 策略模式,“策略”可以實現目標的方案集合。也就是說一件事情,有多種方法可以實現,但根據實際情況的不同,我們要用我們已知的不同方法去實現,即用不同策略應對不同的情況。注意,是已知的方法,也就是說,我們之前準備好的方法

如果是突發事件,策略就沒有用了。這也是策略模式的一個弱點,就是隨着情況的增多,我們相應的策略也要增多。

Strategy適合下列場合:

一、拿開發應用程序來講

1.以不同的格式保存文件;

2.以不同的算法壓縮文件;

3.以不同的算法截獲圖象;

4.以不同的格式輸出同樣數據的圖形,比如曲線 或框圖bar等

二、拿企業業務來講

比如我們做一個收購程序,要給不同的企業用,但不同的企業因各自的差異,他們收購的方式是不一樣的。就拿給收購的產品訂價這件事來講吧,企業1訂價的規則跟企業2訂價規則是不一樣的,可能還有企業3。。。。企業N。我們不可能用一個通用的代碼來實現所有的這些企業的規則。那麼可以用策略模式來做這件事,爲每個企業實現不同的算法,在實際情況中調用相應的算法來給企業計算訂價結果。(這個例子,想來想去都覺得不是很貼切,不過主要是理解,理解就好!)

 

寫了一遍代碼,加深記憶:

首先建立接口,定義功能

package dcr.study.dp.strategy;
public interface IPriceRule {
	float getPrice(String conditions);
	
}

 然後爲不同的情況實現不同的算法

package dcr.study.dp.strategy;

public class PriceRuleOne implements IPriceRule {

	public float getPrice(String conditions) {
		return 1.3f;
	}

}


package dcr.study.dp.strategy;

public class PriceRuleTwo implements IPriceRule {

	public float getPrice(String conditions) {
		return 2.3f;
	}

}


package dcr.study.dp.strategy;

public class PriceRuleThree implements IPriceRule {

	public float getPrice(String conditions) {
		return 3.3f;
	}

}

 再弄個Context 來調用這些算法

package dcr.study.dp.strategy;

public class PriceRuleSolve {
	private IPriceRule strategy;
	public PriceRuleSolve(IPriceRule rule){
		this.strategy = rule;
	}
	
	public float getPriceResult(String conditions){
		return strategy.getPrice(conditions);
	}
}

 最後是實際的使用,根據不同的情況,通過Context調用不同的方法

package dcr.study.dp.strategy;

public class Application {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		PriceRuleSolve solve = new PriceRuleSolve(new PriceRuleOne());
		solve.getPriceResult("input some conditions");
            solve = new PriceRuleSolve(new PriceRuleTwo());
		 solve.getPriceResult("input some conditions");

	}

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章