在 Strategy Pattern中,當一個任務控制器需要處理某項事物的時候,它可以命令他所控制的事務讀取一個configuration file,然后根據(jù)這個file將一些配置信息傳遞給一個接口從而調(diào)用相應的信息,而這個接口可能是一個Aggregation的接口,這個Aggregation可能是一組規(guī)則或者內(nèi)容不一樣,但具有相同的類型或者特點的事務,可以用一個Abstract class讓他們繼承,
這樣統(tǒng)一將對象交給固定接口,而外部只要調(diào)用這個接口即可。
以下是“四人幫”的說法。
Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.[6]


public class TaskController
{

public void process ()
{
// this code is an emulation of a
// processing task controller
// . . .
// figure out which country you are in
CalcTax myTax;
myTax= getTaxRulesForUS();
SalesOrder mySO= new SalesOrder();
mySO.process( myTax);// 當然你還可以讓myTax=getTaxRulesForCan();這樣mySo.process(myTax)就會按照加拿大的稅率處理
}

private CalcTax getTaxRulesForUS()
{
// In real life, get the tax rules based on
// country you are in. You may have the
// logic here or you may have it in a
// configuration file
// Here, just return a USTax so this
// will compile.
return new USTax();
}
}


public class SalesOrder
{

public void process (CalcTax taxToUse)
{
long itemNumber= 0;
double price= 0;

// given the tax object to use

// . . .

// calculate tax
double tax=
taxToUse.taxAmount( itemNumber, price);
}
}


public abstract class CalcTax
{
abstract public double taxAmount(
long itemSold, double price);
}


public class CanTax extends CalcTax
{
public double taxAmount(

long itemSold, double price)
{
// in real life, figure out tax according to
// the rules in Canada and return it
// here, return 0 so this will compile
return 0.0;
}
}

public class USTax extends CalcTax
{
public double taxAmount(

long itemSold, double price)
{
// in real life, figure out tax according to
// the rules in the US and return it
// here, return 0 so this will compile
return 0.0;
}
}

實際整個Strategy的核心部分就是抽象類的使用,使用Strategy模式可以在用戶需要變化時,修改量很少,而且快速.
Strategy和Factory有一定的類似,Strategy相對簡單容易理解,并且可以在運行時刻自由切換。Factory重點是用來創(chuàng)建對象。
Strategy適合下列場合:
1.以不同的格式保存文件;
2.以不同的算法壓縮文件;
3.以不同的算法截獲圖象;
4.以不同的格式輸出同樣數(shù)據(jù)的圖形,比如曲線 或框圖bar等
---------------------------------------------------------
專注移動開發(fā)
Android, Windows Mobile, iPhone, J2ME, BlackBerry, Symbian
posted on 2007-04-07 17:23
TiGERTiAN 閱讀(282)
評論(0) 編輯 收藏 所屬分類:
Design Patterns