随笔 - 1162  文章 - 0  评论 - 16  阅读 - 59万 

一、策略模式在 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 }
复制代码

 

 

 

 

posted on   格物致知_Tony  阅读(107)  评论(0编辑  收藏  举报
编辑推荐:
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· 没有源码,如何修改代码逻辑?
· NetPad:一个.NET开源、跨平台的C#编辑器
· 面试官:你是如何进行SQL调优的?
历史上的今天:
2020-03-03 jQuery — 事件对象
点击右上角即可分享
微信分享提示

目录导航