策略模式:策略模式针对一组算法,将每一个算法封装到具有共同接口的独立的类中,从而使得它们可以相互替换。策略模式使得算法可以在不影响到客户端的情况下发生变化。策略模式把行为和环境分开。环境类负责维持和查询行为类,各种算法在具体的策略类中提供。由于算法和环境独立开来,算法的增减,修改都不会影响 到环境和客户端。
(1)建立一个抽象类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;
}
(2)有一个抽象方法abstract需要继承明确,这个replace里其实是替代的具体方法,示例代码如下:
public class RepTempRuleOne extends RepTempRule{
public void replace() throws Exception{
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");
}
}
(3)我们要建立一个算法解决类,用来提供客户端可以自由选择算法。示例代码如下:
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;
}
}
(4)测试。示例代码如下:
public class StrategyTest {
public static void main(String[] args) throws Exception {
RepTempRuleSolve solver = new RepTempRuleSolve(new RepTempRuleOne());
System.out.println(solver.getNewContext("", "aaabbbaaa"));
solver.changeAlgorithm(new RepTempRuleTwo());
System.out.println(solver.getNewContext("", "aaabbbaaa"));
}
}
示例代码转自:http://www.jdon.com/designpatterns/