java设计模式之策略模式

2,080 阅读1分钟

目录

一、策略模式(Strategy Pattern)

二、 demo:

三、项目地址:


一、策略模式(Strategy Pattern)


策略模式定义了一系列算法,并将每个算法封装起来,使他们可以相互替换,且算法的变化不会影响到使用算法的客户。需要设计一个接口,为一系列实现类提供统一的方法,多个实现类实现该接口,也可以设计一个抽象类(可有可无,属于辅助类),提供辅助函数

策略模式的决定权在用户,系统本身提供不同算法的实现,新增或者删除算法,对各种算法做封装。因此,策略模式多用在算法决策系统中,外部用户只需要决定用哪个算法即可。

二、 demo:


//统一的接口

/**
 * Created by yjl on 2020/9/30.
 * 策略模式:博文介绍链接:https://blog.csdn.net/qq_27471405/article/details/108886135
 * 统一的接口
 */
public interface ICalculator {
    public int calculate(String exp);
}

   //抽象类,作为辅助类,可以提供一些你认为需要的方法

/**
 * Created by yjl on 2020/9/30.
 * 策略模式:博文介绍链接:https://blog.csdn.net/qq_27471405/article/details/108886135
 * 提供算法的方法辅助类
 */
public abstract class AbstractCalculator {

    /**
     * 算法处理方法一
     * @param exp
     * @param opt
     * @return
     */
    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;
    }


    public int[] split2(String exp,String opt){
        System.out.println("这里可以放其他算法等方法");
        return new int[]{2,5,11};
    }
}

    //接口的三个实现类:
PlusService:

/**
 * Created by yjl on 2020/9/30.
 * 策略模式:博文介绍链接:https://blog.csdn.net/qq_27471405/article/details/108886135
 * 加法服务
 */
public class PlusService extends AbstractCalculator implements ICalculator{

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

  

   MinusService:

/**
 * Created by yjl on 2020/9/30.
 * 策略模式:博文介绍链接:https://blog.csdn.net/qq_27471405/article/details/108886135
 * 减法服务
 */
public class MinusService extends AbstractCalculator implements ICalculator {
    @Override
    public int calculate(String exp) {
        int arrayInt[] = split(exp.toString(),"-");
        return arrayInt[0]-arrayInt[1];
    }
}

 MultiplyService:

/**
 * Created by yjl on 2020/9/30.
 * 策略模式:博文介绍链接:https://blog.csdn.net/qq_27471405/article/details/108886135
 * 乘法服务
 */
public class MultiplyService extends AbstractCalculator implements ICalculator {
    @Override
    public int calculate(String exp) {
        int arrayInt[] = split(exp.toString(),"[*]");
        return arrayInt[0]*arrayInt[1];
    }
}

    当然,想要加其他的可以继续加,符合开闭原则,要对扩展开放

//测试类

public class TestStrategy {
    public static void main(String[] args) {
        String exp = "10-3";
        ICalculator cal = new MinusService();
        int result = cal.calculate(exp);
        System.out.println(exp+":"+result);

    }
}

三、项目地址:

github.com/jalenFish/d…