设计模式(十八)之 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;}
具体方法.
我们现在有两个字符替代方案,
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
- 设计模式之(十八)策略模式Strategy
- 设计模式(十八)之 Strategy(策略)
- Strategy策略设计模式(十八)
- 设计模式之Strategy(策略)
- 设计模式之Strategy(策略)
- 设计模式之Strategy(策略)
- 设计模式之Strategy(策略)
- 设计模式之Strategy(策略)
- 设计模式之Strategy(策略)
- 设计模式之Strategy(策略)
- 设计模式之Strategy(策略)
- 设计模式之Strategy(策略)
- 设计模式之Strategy(策略)
- 设计模式之Strategy(策略)
- 设计模式之Strategy(策略)
- 设计模式之Strategy(策略)
- 设计模式 ( 十八 ) 策略模式Strategy(对象行为型)
- 设计模式 ( 十八 ) 策略模式Strategy(对象行为型)
- ashrpt.sql
- 【树链剥分】专题小结
- [php] 静态方法 接口 链式操作
- poj 3723 kruscal,反边取最大生成树。
- 安装keepalived 报错`install' is up to date
- 设计模式(十八)之 Strategy(策略)
- ThinkPHP3.2使用PHPMailer发送邮件
- HDU ACM 4515 小Q系列故事——世界上最遥远的距离
- 英语学习电影资源
- 面试题:Java中对象序列化接口(Serializable)的意义
- 【重构】dll文件是什么
- 无需光驱恢复或重置系统(正常会提示插入介质)
- qtsdk仓库中国镜像
- android中 ImageView scaleType属性