本文最后更新于 2025年7月26日 下午
策略模式 定义了一组算法,将每个算法封装起来,并且使它们之间可以互换
角色
- 抽象的策略 : 一个接口或抽象类
- 具体的策略 : 实现了抽象的策略
- 一个普通的类 : 上下文环境,对抽象策略的引用
实现策略模式
策略模式本身就是 一种多态机制的利用。通过同一个类下的不同实现,来达成根据不同的情况调用不同方法的目的。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| public interface Strategy { void operate(); }
public class GoOutWithRain implements Strategy { public void operate() { System.out.println("带把雨伞出门"); } }
public class GoOutWithSun implements Strategy { public void operate() { System.out.println("穿防晒衣出门"); } }
public class GoOutWithWind implements Strategy { public void operate() { System.out.println("风太大了,不出去了"); } }
public class Context { private Strategy strategy; public Context(Strategy strategy) { this.strategy = strategy; } public void execute() { strategy.operate(); } }
public class Test { public static void main(String[] args) { String weather = "雨天"; Strategy strategy; if (weather.equals("晴天")) { strategy = new GoOutWithSun(); } else if (weather.equals("雨天")) { strategy = new GoOutWithRain(); } else { strategy = new GoOutWithWind(); } Context context = new Context(strategy); context.execute(); } }
|
总结
策略模式(Strategy Pattern)是一种 行为型设计模式 ,它定义了一组算法或行为,将每个算法封装成独立的策略类,并使它们可以相互替换。客户端可以在运行时选择合适的策略,而不必修改使用策略的上下文类。通过将行为抽象提取出来并注入上下文对象,策略模式实现了 行为的封装、解耦与复用 ,特别适用于具有多种变换行为的场景,如支付方式切换、出行策略选择、排序算法替换等。其核心是面向接口编程+组合优于继承的思想。