Strategy Pattern:策略模式,该模式定义了一系列算法,并将每个算法封装起来,使它们可以相互替换,且算法的变化不会影响使用算法的客户。策略模式属于对象行为模式,它通过对算法进行封装,把使用算法的责任和算法的实现分割开来,并委派给不同的对象对这些算法进行管理
说明:实现某一个功能可能存在多种算法和策略,每种算法和策略都有自己的优势和劣势,在不同的条件下选择不同的算法或者策略来完成功能,如最典型的排序算法,有冒泡排序,插入排序,选择排序等,且使用场景不同
策略模式的组成:
- 抽象策略类:Strategy,定义一个公共接口,各个不同的算法实现这个接口,环境角色使用该接口调用不同的策略
- 具体策略类:Concrete Strategy,实现了抽象策略定义的接口,提供具体实现
- 场景类:Context,持有一个策略类的引用,最终给客户端进行调用

public class StrategyDemo {public static void main(String[] args) {Context context = new Context();// 这里使用Lambda来使用策略接口context.setStrategy(Math::min).handle(18,20);context.setStrategy(Math::max).handle(18,20);}// 策略接口static interface Strategy {int calc(int a, int b);}static class Context {private Strategy strategy;public Strategy getStrategy() {return strategy;}public Context setStrategy(Strategy strategy) {this.strategy = strategy;return this;}public void handle(int a, int b) {System.out.println("其他相关处理");// 调用策略方法int calc = strategy.calc(a, b);System.out.println(calc);}}}
