strategy 策略设计模式
定义一系列算法,把这些算法一个个封装成独立的类
示例代码如下
/**
*
* @time 下午08:59:41
* @author retacn yue
* @Email zhenhuayue@sina.com
*/
public abstract class RepTempRule {
protected String oldString = "";
protected String newString = "";
public String getNewString() {
return newString;
}
public void setOldString(String oldString) {
this.oldString = oldString;
}
/**
* 需要替代的具体方法
*
* @throws Exception
*/
public abstract String replace() throws Exception;
}
/**
* 替换方法一
*
* @time 下午09:04:03
* @author retacn yue
* @Email zhenhuayue@sina.com
*/
public class RepTempRuleFirst extends RepTempRule {
@Override
public String replace() throws Exception {
newString = oldString.replace("aaaa", "bbbb");
System.out.println("this is first replace method ");
return null;
}
}
/**
* 替换方法二
*
* @time 下午09:04:03
* @author retacn yue
* @Email zhenhuayue@sina.com
*/
public class RepTempRuleSecond extends RepTempRule {
@Override
public String replace() throws Exception {
newString = oldString.replace("aaaa", "cccc");
System.out.println("this is second replace method ");
return null;
}
}
/**
* 算法解决类
*
* 客户自由选择算法
*
* @time 下午09:06:23
* @author retacn yue
* @Email zhenhuayue@sina.com
*/
public class RepTempRuleSolve {
private RepTempRule strategy;
/**
* 构造器
*
* @param strategy
*/
public RepTempRuleSolve(RepTempRule strategy) {
this.strategy = strategy;
}
public String getNewContext() {
String temp = null;
try {
temp = strategy.replace();
} catch (Exception e) {
e.printStackTrace();
}
return temp;
}
/**
* 算法选择
*/
public void changeAlgorithm(RepTempRule newAlgorithm) {
strategy = newAlgorithm;
}
}
/**
* 测试策略模式
*
* @time 下午09:14:49
* @author retacn yue
* @Email zhenhuayue@sina.com
*/
public class TestRepTempRule {
public static void main(String[] args) {
// 方法一
RepTempRuleSolve solve = new RepTempRuleSolve(new
RepTempRuleFirst());
solve.getNewContext();
// 方法二
solve = new RepTempRuleSolve(new RepTempRuleSecond());
solve.getNewContext();
}
}
java 设计模式学习笔记十五 strategy 策略设计模式
最新推荐文章于 2024-09-02 18:19:21 发布