设计模式 互动版

策略模式例子

现在我们要根据不同需求,计算两个数的四则运算( + - * /)

//策略定义算法的接口
public interface Strategy {
    int calculate(int num1,int num2);
}
//具体算法,加法
public class OperationAdd implements Strategy {
    @Override
    public int calculate(int num1, int num2) {
        return num1 + num2;
    }
}
//具体算法,减法
public class OperationSubstract implements Strategy {
    @Override
    public int calculate(int num1, int num2) {
        return num1 - num2;
    }
}
//具体算法,乘法
public class OperationMultiply implements Strategy {
    @Override
    public int calculate(int num1, int num2) {
        return num1 * num2;
    }
}
//具体算法,除法
public class OperationDivide implements Strategy {
    @Override
    public int calculate (int num1, int num2){
        int res = 0;
        try {
            res = num1 / num2;
        }catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }
}
//上下文
public class Context {
    //持有一个具体策略对象
    private Strategy strategy;

    //传入一个具体策略对象
    public Context(Strategy strategy) {
        this.strategy =strategy;
    }

    public int calculate(int num1,int num2){
        //调用具体策略对象进行算法运算
        return strategy.calculate(num1,num2);
    }
}
public static void main(String[] args) {
    //计算 1 + 1
    Context context = new Context(new OperationAdd());
    System.out.println("1 + 1 = " + context.calculate(1,1));
    //计算 1 - 1
    context = new Context(new OperationSubstract());
    System.out.println("1 - 1 = " +context.calculate(1,1));
}

输出结果:

jquery