首先,我们建立一个抽象类RepTempRule 定义一些公用变量和方法:
public abstract class RepTempRule{
protected String oldString";
protected String newString;
public void setOldString(String oldString){
this.oldString=oldString;
}
public String getNewString(){
return newString;
}
public abstract void replace() throws Exception;
}
public class RepTempRuleOne extends RepTempRule{
public void replace() throws Exception{
newString=oldString.replaceFirst("aaa", "bbbb")
//replaceFirst是jdk有的方法
System.out.println("this is replace one");
}
}
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;
}
}
RepTempRuleSolve solver=new RepTempRuleSolve(new RepTempRuleSimple());
solver.getNewContext(site,context);
//使用第二套
solver=new RepTempRuleSolve(new RepTempRuleTwo());
solver.getNewContext(site,context);
Android开发之策略模式初探,布布扣,bubuko.com
原文:http://blog.csdn.net/gerogelin/article/details/38655809