看了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{
@Override
public String replace() throws Exception {
// TODO Auto-generated method stub
newString=oldString.replaceFirst("aaa", "XXX");
return newString ;
}
}
public class RepTempRuleTwo extends RepTempRule{
@Override
public String replace() throws Exception {
// TODO Auto-generated method stub
newString=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 block
e.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等