策略模式

893 查看

描述:某项业务需要根据不同的要求(算法)计算结果,这些要求之间彼此独立。

场景:实现一个计算器,要有加减乘除法则,这些法则就是不同的算法,计算器仅需根据法则的标记计算结果。

实现:

抽象算法接口

interface Strategy {
    void calc(int a, int b);
}

定义加法

class Add implements Strategy {
    @Override
    public void calc(int a, int b) {
        System.out.println(String.format("%d + %d = %d", a, b, (a + b)));
    }
}

定义减法

class Sub implements Strategy {
    @Override
    public void calc(int a, int b) {
        System.out.println(String.format("%d - %d = %d", a, b, (a - b)));
    }
}

定义一个计算器

class Calculator {

    static Map<String, Strategy> strategys = 
                                        new HashMap<String, Strategy>();

    static {
        strategys.put("+", new Add());
        strategys.put("-", new Sub());
    }

    static void calc(int a, String flag, int b) {
        Strategy strategy = strategys.get(flag);
        strategy.calc(a, b);
    }
}

启动计算器

public class StrategyDemo {
    public static void main(String[] args) {
        Calculator.calc(4, "-", 6);// =-2
        Calculator.calc(4, "+", 6);// =10
    }
}