策略模式

场景:

以字符串替代为例:

有一个文件,我们需要读取后,希望替代其中相应的变量,然后输出。关于替代其中变量的方法可能有多种方法,这取决于用户的要求,所以我们要准备几套变量字符替代方案。

创建一个抽象类RepTempRule。

View Code
package designModel.stratrgy;

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 String replace() throws Exception ;
}

在RepTempRule 中 有一个抽象方法abstract 需要继承明确,这个replace 里其实是替代的
具体方法.
我们现在有两个字符替代方案,
1.将文本中aaa 替代成bbb;
2.将文本中aaa 替代成ccc;
对应的类分别是RepTempRuleOne和RepTempRuleTwo

package designModel.stratrgy;

public class RepTempRuleOne extends RepTempRule{

    public RepTempRuleOne(String oldString){
        this.oldString = oldString ;
    }
    
    public String replace() throws Exception {
        newString = oldString.replaceFirst("aaa", "bbbb") ;
        System.out.println("this is the repalce one !");
        return newString ;
    }
    
}

RepTempRuleTwo

package designModel.stratrgy;

public class RepTempRuleTwo extends RepTempRule{

    public RepTempRuleTwo(String oldString){
        this.oldString = oldString ;
    }
    
    public String replace() throws Exception {
        newString = oldString.replaceFirst("aaa", "ccc");
        System.out.println("this is the replace two ! ");
        return newString ;
    }
    
}

建立一个算法解决类,用来提供客户端可以自由选择算法。

package designModel.stratrgy;

public class RepTempRuleSolve {
    
    private RepTempRule strategy;
    
    public RepTempRuleSolve(RepTempRule rule){
        this.strategy=rule;
    }
    
    public String getNewContext() throws Exception {
        return strategy.replace();
    }
    
    /**
     * 改变策略
     * @param newAlgorithm
     */
    public void changeAlgorithm(RepTempRule newAlgorithm) {
        strategy = newAlgorithm;
    }
}

调用:

package designModel.stratrgy;

/**
 * 通过策略模式,我们达到了在运行期间自由切换算法的目的。
 * 整个Strategy的核心部分就是抽象类的使用,使用策略模式可以在用户需求变化时,
 * 修改量很少,而且速度很快。
 * 适用场合:
 * 1、以不同格式保存文件;
 * 2、以不同算法压缩文件
 * 3、以不同是算法截获图像。
 * @author slpei
 *
 */
public class Test {
    public static void main(String args[]) throws Exception{
        
        String newString = "" ;
        
        //使用第一套替代方案
        RepTempRuleSolve solver=new RepTempRuleSolve(new RepTempRuleOne("aaabncv"));
        newString = solver.getNewContext();
        System.out.println(newString);
        
        //使用第二套
        solver.changeAlgorithm(new RepTempRuleTwo("aaabncv")) ;
        newString = solver.getNewContext();
        System.out.println(newString);
    }
}

在Test类中我们可以自由切换算法

原文地址:https://www.cnblogs.com/peislin/p/2576135.html