美文网首页
策略模式

策略模式

作者: 全栈未遂工程师 | 来源:发表于2016-03-21 16:36 被阅读24次

策略模式(Strategy):定义了算法家族,分别封装起来,让他们之间可以互相替换,此模式让算法的变化,不会影响到使用算法的客户。

策略模式
package com.strategy;
//所有策略的一个接口
public interface CalculatorInterface {
    public int calculate(String exp);
}

package com.strategy;
//辅助类
public class AbstractCalculator {
    public int[] split(String exp, String opt){
        String[] array = exp.split(opt);
        int[] arrInt = new int[2];
        arrInt[0] = Integer.parseInt(array[0].trim());
        arrInt[1] = Integer.parseInt(array[1].trim());
        return arrInt;
    }
}
package com.strategy;

public class Plus extends AbstractCalculator implements CalculatorInterface{
    @Override
    public int calculate(String exp) {
        int[] arrI = this.split(exp, "\\+");
        return arrI[0] + arrI[1];
    }
}
package com.strategy;
/**
 * ClassName: Main 
 * @Description:策略模式(strategy):
    策略模式定义了一系列算法,并将每个算法封装起来,使他们可以相互替换,且算法的变化不会影响到使用算法的客户。
    需要设计一个接口,为一系列实现类提供统一的方法,多个实现类实现该接口,设计一个抽象类(可有可无,属于辅助类),提供辅助函数。
    策略模式的决定权在用户,系统本身提供不同算法的实现,新增或者删除算法,对各种算法做封装。
    因此,策略模式多用在算法决策系统中,外部用户只需要决定用哪个算法即可。
 * @author Panyk
 * @date 2015年10月14日
 */
public class Main {
    public static void main(String[] args) {
        CalculatorInterface ci = new Plus();
        String exp = "3+8";
        int res = ci.calculate(exp);
        System.out.println(exp + " = " + res);
    }
}

相关文章

网友评论

      本文标题:策略模式

      本文链接:https://www.haomeiwen.com/subject/chvklttx.html