一、策略模式在 JDK-Arrays 应用的源码分析
1、JDK 的 Arrays 的 Comparator 就使用了策略模式
2、代码
1 public class StrategyTest {
2 public static void main(String[] args) {
3 Integer[] data = {9, 1, 2, 8, 4, 3};
4
5
6 /**
7 * 1、实现了 Compartor 接口(策略接口),匿名类对象 new Compareator()
8 * 2、new Comparator<Integer>() {} 就是实现了 策略接口的对象
9 * 3、public int compare(Integer o1, Integer o2) {} 指定具体的处理方式
10 */
11 Comparator<Integer> comparator = new Comparator<Integer>() {
12
13 @Override
14 public int compare(Integer o1, Integer o2) {
15 if (o1 > o2) {
16 return 1;
17 } else {
18 return -1;
19 }
20 }
21 };
22
23 /**
24 * 方式一:策略模式
25 * public static <T> void sort(T[] a, Comparator<? super T> c) {
26 * if (c == null) {
27 * sort(a); 默认方法
28 * } else {
29 * if (LegacyMergeSort.userRequested)
30 * legacyMergeSort(a, c); //使用策略模式对象
31 * else
32 * //使用策略对象 c
33 * TimSort.sort(a, 0, a.length, c, null, 0, 0);
34 * }
35 * }
36 *
37 */
38 Arrays.sort(data, comparator);
39
40 //升序
41 System.out.println(Arrays.toString(data));
42
43 //方式二
44 Integer[] data2 = {19, 11, 12, 18, 14, 13};
45
46 Arrays.sort(data2, new Comparator<Integer>() {
47 @Override
48 public int compare(Integer o1, Integer o2) {
49 if (o1 > o2) {
50 return -1;
51 } else {
52 return 1;
53 }
54 }
55 });
56
57 System.out.println(Arrays.toString(data2));
58 }
59 }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· 没有源码,如何修改代码逻辑?
· NetPad:一个.NET开源、跨平台的C#编辑器
· 面试官:你是如何进行SQL调优的?
2020-03-03 jQuery — 事件对象