`
dev_liu
  • 浏览: 109425 次
  • 性别: Icon_minigender_1
  • 来自: 成都
最近访客 更多访客>>
社区版块
存档分类
最新评论

设计模式之Strategy(策略)

阅读更多

Strategy 是属于设计模式中 对象行为型模式,主要是定义一系列的算法,把这些算法一个
个封装成单独的类.
Stratrgy 应用比较广泛,比如, 公司经营业务变化图, 可能有两种实现方式,一个是线条曲
线,一个是框图(bar),这是两种算法,可以使用Strategy 实现.
这里以字符串替代为例, 有一个文件,我们需要读取后,希望替代其中相应的变量,然后输出.
关于替代其中变量的方法可能有多种方法,这取决于用户的要求,所以我们要准备几套变量
字符替代方案.
首先,我们建立一个抽象类RepTempRule 定义一些公用变量和方法:
public abstract class RepTempRule{
protected String oldString="";
public void setOldString(String oldString){
this.oldString=oldString;
}
protected String newString="";

public String getNewString(){
return newString;
}
public abstract void replace() throws Exception;
}
在RepTempRule 中 有一个抽象方法abstract 需要继承明确,这个replace 里其实是替代的
具体方法.
我们现在有两个字符替代方案,
1.将文本中aaa 替代成bbb;
2.将文本中aaa 替代成ccc;
对应的类分别是RepTempRuleOne RepTempRuleTwo
public class RepTempRuleOne extends RepTempRule{
public void replace() throws Exception{
//replaceFirst 是jdk1.4 新特性
newString=oldString.replaceFirst("aaa", "bbbb")
System.out.println("this is replace one");
}
}
public class RepTempRuleTwo extends RepTempRule{
public void replace() throws Exception{
newString=oldString.replaceFirst("aaa", "ccc")
System.out.println("this is replace Two");
}
}
第二步:我们要建立一个算法解决类,用来提供客户端可以自由选择算法。
public class RepTempRuleSolve {
private RepTempRule strategy;
public RepTempRuleSolve(RepTempRule rule){
this.strategy=rule;
}
public String getNewContext(Site site,String oldString) {
return strategy.replace(site,oldString);
}
public void changeAlgorithm(RepTempRule newAlgorithm) {
strategy = newAlgorithm;
}
}
调用如下:
public class test{
......
public void testReplace(){
//使用第一套替代方案
RepTempRuleSolve solver=new RepTempRuleSolve(new RepTempRuleSimple());
solver.getNewContext(site,context);
//使用第二套
solver=new RepTempRuleSolve(new RepTempRuleTwo());
solver.getNewContext(site,context);
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics