策略模式
# 策略模式
策略模式是行为型设计模式,核心是将算法/业务策略封装为独立的策略类,使策略可灵活替换、扩展,且策略的变化不影响使用策略的客户端,遵循开闭原则和单一职责原则。
核心角色(4 个)
抽象策略(Strategy):定义策略的公共接口 / 抽象类,声明核心执行方法(如doOperation()),约束所有具体策略的行为。
具体策略(ConcreteStrategy):实现抽象策略接口,封装具体的算法 / 业务逻辑(如策略 A、策略 B),可按需新增。
环境 / 上下文(Context):持有抽象策略的引用,提供给客户端调用的入口,负责策略的切换和执行,不直接实现业务逻辑。
客户端(Client):根据需求选择具体的策略,注入到上下文对象中,调用上下文的执行方法完成业务。
# 案例一
- 抽象策略(Strategy)
// 抽象计算策略
public interface CalculateStrategy {
int calculate(int a, int b); // 核心执行方法
}
1
2
3
4
2
3
4
- 具体策略(ConcreteStrategy)
// 具体策略:加法
public class AddStrategy implements CalculateStrategy {
@Override
public int calculate(int a, int b) {
return a + b;
}
}
1
2
3
4
5
6
7
2
3
4
5
6
7
// 具体策略:减法
public class SubtractStrategy implements CalculateStrategy {
@Override
public int calculate(int a, int b) {
return a - b;
}
}
1
2
3
4
5
6
7
2
3
4
5
6
7
- 上下文(Context)
// 上下文:持有策略引用,提供执行入口
public class CalculateContext {
// 抽象策略引用(核心:面向抽象编程)
private CalculateStrategy strategy;
// 注入策略(客户端设置,支持动态切换)
public void setStrategy(CalculateStrategy strategy) {
this.strategy = strategy;
}
// 客户端调用的统一入口
public int executeCalculate(int a, int b) {
return strategy.calculate(a, b);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
- 客户端(Client)
// 客户端:选择并使用策略
public class Client {
public static void main(String[] args) {
CalculateContext context = new CalculateContext();
int a = 10, b = 5;
// 选择加法策略
context.setStrategy(new AddStrategy());
System.out.println(a + " + " + b + " = " + context.executeCalculate(a, b)); // 15
// 动态切换为减法策略
context.setStrategy(new SubtractStrategy());
System.out.println(a + " - " + b + " = " + context.executeCalculate(a, b)); // 5
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Last Updated: 2026/01/30, 11:41:22