设计模式课程 设计模式精讲 19-3 策略模式源码解析

1    源码解析

1.1    源码解析1(jdk中的应用1)

1.2    源码解析2jdk中的应用2

1.3    源码解析3(Spring中的应用1)

1.4    源码解析4Spring中的应用2

1    源码解析
1.1    源码解析1(jdk中的应用1

java.util.Comparator(策略类)作为比较器的应用

package java.util;


public interface Comparator<T> {
  
    int compare(T o1, T o2);

    boolean equals(Object obj);
}

java.util.ArrayList(策略类应用)

package java.util;

import java.lang.reflect.*;

public class Arrays {

    public static <T> void sort(T[] a, Comparator<? super T> c) {
        if (LegacyMergeSort.userRequested)
            legacyMergeSort(a, c);
        else
            TimSort.sort(a, c);
    }

}
1.2    源码解析2jdk中的应用2

java.util.Comparator(策略类)作为比较器的应用

package java.util;


public interface Comparator<T> {
  
    int compare(T o1, T o2);

    boolean equals(Object obj);
}

java.util.TreeMap(策略类应用)

public class TreeMap<K,V>
    extends AbstractMap<K,V>
    implements NavigableMap<K,V>, Cloneable, java.io.Serializable
{
    /**
     * The comparator used to maintain order in this tree map, or
     * null if it uses the natural ordering of its keys.
     *
     * @serial
     */
    private final Comparator<? super K> comparator;

   final int compare(Object k1, Object k2) {
        return comparator==null ? ((Comparable<? super K>)k1).compareTo((K)k2)
            : comparator.compare((K)k1, (K)k2);
    }
}

 

相关推荐