策略模式的作用:定义了一系列算法,并将每个算法封装起来,使它们可以相互替换,且算法的改变不会影响使用算法的客户。
案例
java.util.Comparator 接口定义元素之间的比较方法,如,有 compare 方法
public interface Comparator<T> {
int compare(T o1, T o2);
}
Arrays 工具类,指定 Comparator 进行排序
public class Arrays {
public static void sort(int[] a) {
DualPivotQuicksort.sort(a, 0, a.length - 1, null, 0, 0);
}
}
java.util.List,指定 Comparator 进行排序
public interface List<E> extends Collection<E> {
@SuppressWarnings({"unchecked", "rawtypes"})
default void sort(Comparator<? super E> c) {
Object[] a = this.toArray();
Arrays.sort(a, (Comparator) c);
ListIterator<E> i = this.listIterator();
for (Object e : a) {
i.next();
i.set((E) e);
}
}
}
TreeMap 构造方法指定 Comparator,put 元素时,进行比较、排序
public class TreeMap<K,V> extends AbstractMap<K,V> implements NavigableMap<K,V>, Cloneable, java.io.Serializable {
//构造方法指定 key 元素的 comparator
public TreeMap(Comparator<? super K> comparator) {
this.comparator = comparator;
}
//指定了 key 元素的 comparator,存入数据时,使用 comparator 进行比较,否则要求 key 实现 Comparable 接口
public V put(K key, V value) {
...
Comparator<? super K> cpr = comparator;
if (cpr != null) {
do {
parent = t;
cmp = cpr.compare(key, t.key);
if (cmp < 0)
t = t.left;
else if (cmp > 0)
t = t.right;
else
return t.setValue(value);
} while (t != null);
}
else {
...
Comparable<? super K> k = (Comparable<? super K>) key;
do {
parent = t;
cmp = k.compareTo(t.key);
if (cmp < 0)
t = t.left;
else if (cmp > 0)
t = t.right;
else
return t.setValue(value);
} while (t != null);
}
...
}
}
这里的 Comparator 接口就是使用了策略模式,实际使用中 implements Comparator 接口或者使用接口的匿名实现类,根据需求实现不同比较逻辑的算法策略。当然这里并没有内置不同策略的实现,而是放开给程序员自己实现。
扫描二维码关注公众号,回复:
11644659 查看本文章
【Java学习资源】整理推荐
- 策略模式在开源代码中应用
- 模板方法模式在开源代码中应用
- 组合模式在开源代码中的应用
- 享元模式在开源代码中的应用
- 外观模式在开源代码中的应用
- 装饰器模式在开源代码中的应用
- 桥接模式在开源代码中的应用
- 适配器模式在开源代码中的应用
- 代理模式在开源代码中的应用
- 原型模式在开源代码中的应用
- 建造者模式在开源代码中的应用
- 工厂模式在开源代码中的应用
- 单例模式在开源代码中的应用
- 编码规范
- 设计模式
- 重构
- 设计原则
- 面向对象到底是什么
- 代码质量有哪些评判标准?