模式介绍

策略模式是一种行为型设计模式,它定义了一系列算法,并将每个算法封装起来,使它们可以互相替换。策略模式让算法的变化独立于使用算法的客户端。

使用场景

  • 当需要在运行时选择算法时
  • 当一个类定义了多种行为,并且这些行为在这个类的操作中以多个条件语句的形式出现时
  • 当算法涉及复杂的条件语句时

代码示例

// 策略接口
public interface Strategy {
    int doOperation(int num1, int num2);
}

// 具体策略A:加法
public class OperationAdd implements Strategy {
    @Override
    public int doOperation(int num1, int num2) {
        return num1 + num2;
    }
}

// 具体策略B:减法
public class OperationSubtract implements Strategy {
    @Override
    public int doOperation(int num1, int num2) {
        return num1 - num2;
    }
}

// 上下文类
public class Context {
    private Strategy strategy;

    public Context(Strategy strategy) {
        this.strategy = strategy;
    }

    public void setStrategy(Strategy strategy) {
        this.strategy = strategy;
    }

    public int executeStrategy(int num1, int num2) {
        return strategy.doOperation(num1, num2);
    }
}

优缺点

优点

  • 算法可以自由切换
  • 避免使用多重条件判断
  • 扩展性良好

缺点

  • 策略类会增多
  • 所有策略类都需要对外暴露
  • 客户端必须知道所有的策略类