zoukankan      html  css  js  c++  java
  • 第三节:策略模式——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 }

     

     

  • 相关阅读:
    JS重修札记
    backbone简单札记
    通用前端开发框架(一)
    两天低效编程总结
    使用HTTP请求 查找指定位置附近的景点(GOOGLE 地图)
    Google Map上,加上座標點(POIs)
    iphone 反向地理解析 从坐标获得用户的具体位置信息
    iphone 计算大文件md5
    c#多线程下载
    iphone http同步 异步请求
  • 原文地址:https://www.cnblogs.com/niujifei/p/14477657.html
Copyright © 2011-2022 走看看