1. 策略模式
策略模式是一种行为型设计模式,主要思想是定义一系列算法策略,把它们单独封装起来,并且使它们可以互相替换。这样客户端可以根据需要选择不同的算法策略,而不需要改变使用算法策略的上下文,实现了业务逻辑与算法实现的解耦。它的关键是定义一个通用策略接口,然后根据需要创建该接口的实现类,完成独立算法策略的实现。
策略模式的优势,提高代码的维护性和扩展性,同时也保证了低耦合和高内聚的设计原则。
- 开闭原则,新增策略时无需修改已有的策略代码。
- 职责清晰,每个策略实现只关注自身的业务逻辑
- 灵活组合,可以搭配工厂模式,装饰器模式等实现策略增强
- 测试友好,每个策略可以单独进行单元测试
2. 举例实现
核心组件
Strategy Interface (策略接口):定义通用算法接口
Concrete Strategy (具体策略):实现具体算法的策略类
public interface StrategyInterface {
String executeStrategy(String strategy);
}
@Serivce
public class FirstStrategy implements StrategyInterface {
@Override
public String executeStrategy(String strategy){
return "execute first strategy";
}
}
@Serivce
public class SecondStrategy implements StrategyInterface {
@Override
public String executeStrategy(String strategy){
return "execute second strategy";
}
}
public class StrategyDemo{
public static void main(String[] args) {
HashMap<String, StrategyInterface> strategyMap = new HashMap<>();
strategyMap.put("firstStrategy", new FirstStrategy());
strategyMap.put("secondStrategy", new SecondStrategy());
//需要执行first strategy
FirstStrategy firstStrategy = strategyMap.get("firstStrategy");
firstStrategy.executeStrategy("需要变更为执行参数");
//需要执行second strategy
SecondStrategy secondStrategy= strategyMap.get("secondStrategy");
secondStrategy.executeStrategy("需要变更为执行参数");
}
}
在Spingboot中,可以在策略实现类增加Service注解,通过Autowired注入,增加选择策略的参数。
public class StrategyService{
@Autowired
private final Map<String, StrategyInterface> strategyMap = new ConcurrentHashMap<String, StrategyInterface>();
public StrategyInterface get(String strategy) {
StrategyInterface strategy = strategyMap.get(strategy);
if (strategy != null) {
return strategy;
} else {
throw new RuntimeException();
}
}
}
3. 注意事项
- 所有策略是否实现统一接口
- 策略实现与业务处理逻辑边界是否清晰,上下文是否妥善处理策略所需参数
- 策略管理方式是否合适(新建/复用)
- 异常处理机制是否合适
当然在实际开发过程中可能遇到其他问题,这就需要我们进行完整的测试了。
4. 适用场景
- 支付渠道选择
- 营销折扣策略(满减、折扣、优惠券)
- 数据加密算法切换
- 导航路径策略(最快路线、最少收费等)
- 。。。