第三节:策略模式——JDK-Arrays的源码分析

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

 

 

原文地址:https://www.cnblogs.com/niujifei/p/14477657.html