通知 网站从因情语写改为晴雨,这个网站的模板也从calmlog_ex改为 whimurmur

行为型模式-策略模式

207人浏览 / 0人评论 / | 作者:因情语写  | 分类: 设计模式与算法  | 标签: 设计模式与算法

作者:因情语写

链接:https://www.qingyu.blue/article/450

声明:请尊重原作者的劳动,如需转载请注明出处


  行为型模式又可以分成以下四类:第一类:通过父类与子类的关系进行实现。第二类:两个类之间。第三类:类的状态。第四类:通过中间类

  策略模式属于第一类,父类与子类的关系

  即处理一个问题可以采取的不同算法,同时对算法进行封装

  以计算为例

package behavior.pattern.extend.strategy;

public interface ICaculator {
    public int caculate(String exp);
}
package behavior.pattern.extend.strategy;

public abstract class AbstractCalculator {
    public int[] split(String exp,String opt){  
        String array[] = exp.split(opt);
        int arrayInt[] = new int[2];  
        arrayInt[0] = Integer.parseInt(array[0]);  
        arrayInt[1] = Integer.parseInt(array[1]);  
        return arrayInt;  
    }  
}
package behavior.pattern.extend.strategy;

public class Plus extends AbstractCalculator implements ICaculator {

    @Override
    public int caculate(String exp) {
        int arrayInt[] = split(exp,"\\+");  
        return arrayInt[0]+arrayInt[1];  
    }

}
package behavior.pattern.extend.strategy;

public class Minus extends AbstractCalculator implements ICaculator {

    @Override
    public int caculate(String exp) {
        int arrayInt[] = split(exp,"\\-");  
        return arrayInt[0]-arrayInt[1];
    }

}
package behavior.pattern.extend.strategy;

public class Multiply extends AbstractCalculator implements ICaculator{

    @Override
    public int caculate(String exp) {
        int arrayInt[] = split(exp,"\\*");  
        return arrayInt[0]*arrayInt[1];
    }

}
package behavior.pattern.extend.strategy;

public class CaculateStrategy{
    private ICaculator caculator;

    public CaculateStrategy(ICaculator caculator) {
        super();
        this.caculator = caculator;
    }

    public void setCaculator(ICaculator caculator) {
        this.caculator = caculator;
    }
    
    public int caculate(String exp)
    {
        return caculator.caculate(exp);
    }
}

  测试代码

package behavior.pattern.extend.strategy;

public class Client {
    public static void main(String[] args) {
        CaculateStrategy caculateStrategy = new CaculateStrategy(new Plus());
        int plus = caculateStrategy.caculate("1+2");
        System.out.println(plus);
        caculateStrategy.setCaculator(new Multiply());
        int multiply = caculateStrategy.caculate("5*6");
        System.out.println(multiply);
        caculateStrategy.setCaculator(new Minus());
        int minus = caculateStrategy.caculate("10-3");
        System.out.println(minus);
    }
}

  运行结果


亲爱的读者:有时间可以点赞评论一下

点赞(0) 打赏

全部评论

还没有评论!