- JDK的 Arrays 的Comparator就使用了策略模式
| public class Strategy { |
| public static void main(String[] args) { |
| Integer[] data = { 9,1,2,8,4,3 }; |
| |
| Comparator<Integer> comparator = new Comparator<Integer>() { |
| public int compare(Integer o1, Integer o2) { |
| if(o1 > o2) { |
| return 1; |
| }else{ |
| return -1; |
| } |
| }; |
| }; |
| Arrays.sort(data, comparator); |
| System.out.println(Arrays.toString(data)); |
| } |
| } |
| |
| public static <T> void sort(T[] a, Comparator<? super T> c) { |
| if (c == null) { |
| sort(a); |
| } else { |
| if (LegacyMergeSort.userRequested) |
| legacyMergeSort(a, c); |
| else |
| TimSort.sort(a, 0, a.length, c, null, 0, 0); |
| } |
| } |
| |
| public interface Comparator<T> { |
| int compare(T o1, T o2); |
| } |
| 1) 策略模式的关键是:分析项目中变化部分与不变部分 |
| 2) 策略模式的核心思想是:多用组合/聚合 少用继承;用行为类组合,而不是行为的继承。更有弹性 |
| 3) 体现了“对修改关闭,对扩展开放”原则,客户端增加行为不用修改原有代码,只要添加一种策略(或者行为)即可,避免了使用多重转移语句(if..else if..else) |
| 4) 提供了可以替换继承关系的办法: 策略模式将算法封装在独立的Strategy类中使得你可以独立于其Context改变它,使它易于切换、易于理解、易于扩展 |
| 5) 需要注意的是:每添加一个策略就要增加一个类,当策略过多是会导致类数目庞大 |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?