定义了一系列算法,并将每个算法封装起来,使它们可以相互替换,且算法的改变不会影响使用算法的客户。

    【角色】

    • 环境角色(Context):持有一个Strategy的引用。也就是Context内部需要用到某种算法,在策略模式中这种算法是以无缝切换到另一种算法。
    • 抽象策略角色(Strategy):这是一个抽象角色,通常由一个接口或抽象类实现。此角色给出所有的具体策略类所需的接口。
    • 具体策略角色(ConcreteStrategy):包装了相关的算法或行为。

    【优点】

    • 算法可以自由切换,改一下策略很方便。
    • 扩展性良好,增加一个策略,就多增加一个类就好了。

    【缺点】

    • 策略类的数量增多,每一个策略都是一个类,复用的可能性很小、类数量增多。
    • 上层模块必须知道有哪些策略,然后才能决定使用哪一个策略。

      1. /**
      2. * 抽象策略接口
      3. */
      4. public interface Strategy {
      5. int operate(int num1, int num2);
      6. }
      1. /**
      2. * 加法运算
      3. */
      4. public class OperationAdd implements Strategy {
      5. @Override
      6. public int operate(int num1, int num2) {
      7. return num1 + num2;
      8. }
      9. }
      1. /**
      2. * 减法运算
      3. */
      4. public class OperationSub implements Strategy {
      5. @Override
      6. public int operate(int num1, int num2) {
      7. return num1 - num2;
      8. }
      9. }
      1. /**
      2. * 运算
      3. */
      4. public class Context {
      5. private Strategy strategy;
      6. public Context(Strategy strategy) {
      7. this.strategy = strategy;
      8. }
      9. public int execute(int num1, int num2) {
      10. return strategy.operate(num1, num2);
      11. }
      12. }
      1. public class StrategyTest {
      2. public static void main(String[] args) {
      3. // 加法策略
      4. Context context = new Context(new OperationAdd());
      5. System.out.println("10 + 6 = " + context.execute(10, 6));
      6. // 减法策略
      7. context = new Context(new OperationSub());
      8. System.out.println("10 - 6 = " + context.execute(10, 6));
      9. }
      10. }
      11. ----输出----
      12. 10 + 6 = 16
      13. 10 - 6 = 4