随笔-348  评论-598  文章-0  trackbacks-0
在 Strategy Pattern中,当一个任务控制器需要处理某项事物的时候,它可以命令他所控制的事务读取一个configuration file,然后根据这个file将一些配置信息传递给一个接口从而调用相应的信息,而这个接口可能是一个Aggregation的接口,这个Aggregation可能是一组规则或者内容不一样,但具有相同的类型或者特点的事务,可以用一个Abstract class让他们继承,
这样统一将对象交给固定接口,而外部只要调用这个接口即可。
以下是“四人帮”的说法。
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重点是用来创建对象。

Strategy适合下列场合:

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

2.以不同的算法压缩文件;

3.以不同的算法截获图象;

4.以不同的格式输出同样数据的图形,比如曲线 或框图bar等



---------------------------------------------------------
专注移动开发

Android, Windows Mobile, iPhone, J2ME, BlackBerry, Symbian
posted on 2007-04-07 17:23 TiGERTiAN 阅读(269) 评论(0)  编辑  收藏 所属分类: Design Patterns

只有注册用户登录后才能发表评论。


网站导航: