设计模式(十八)之 Strategy(策略)

来源:互联网 发布:爱知工科大学怎么样 编辑:程序博客网 时间:2024/06/08 07:19

定义:

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);
<pre name="code" class="html">}
}








0 0
原创粉丝点击