该模式定义了一系列算法,并将每个算法封装起来,使它们可以相互替换,且算法的变化不会影响使用算法的客户。策略模式属于对象行为模式,它通过对算法进行封装,把使用算法的责任和算法的实现分割开来,并委派给不同的对象对这些算法进行管理。
策略模式的主要角色如下:
抽象策略类
- public interface Strategy {
- void show();
- }
创建具体策略类
- public class StrategyA implements Strategy {
- @Override
- public void show() {
- System.out.println("策略A展示");
- }
- }
-
- public class StrategyB implements Strategy {
- @Override
- public void show() {
- System.out.println("策略B展示");
- }
- }
创建环境类
- public class SalesMan {
- private Strategy strategy;
-
- public SalesMan(Strategy strategy) {
- this.strategy = strategy;
- }
-
- public void show(){
- strategy.show();
- }
- }
测试
- public class Client {
- public static void main(String[] args) {
- SalesMan salesMan = new SalesMan(new StrategyA());
- salesMan.show();
- System.out.println("==============");
- salesMan = new SalesMan(new StrategyB());
- salesMan.show();
- }
- }
运行结果如下
策略A展示
==============
策略B展示
使用哪种策略由客户端来决定,但是需要通过一个环境类(SalesMan)来执行具体策略
Arrays中的sort中的Comparator参数使用的是策略模式
- public class demo {
- public static void main(String[] args) {
-
- Integer[] data = {12, 2, 3, 2, 4, 5, 1};
- // 实现降序排序
- Arrays.sort(data, new Comparator
() { - public int compare(Integer o1, Integer o2) {
- return o2 - o1;
- }
- });
- System.out.println(Arrays.toString(data)); //[12, 5, 4, 3, 2, 2, 1]
- }
- }
进入sort方法可以看到
- public static
void sort(T[] a, Comparator super T> c) { - if (c == null) {
- sort(a);
- } else {
- if (LegacyMergeSort.userRequested)
- legacyMergeSort(a, c);
- else
- TimSort.sort(a, 0, a.length, c, null, 0, 0);
- }
- }
对参数进行判断,查看是否重写了compare()方法,因此可以判断出Comparator类中compare方法是可以进行重写的即,Comparator是一个抽象策略类。如果重写的话进入TimSort中的sort方法
- static
void sort(T[] a, int lo, int hi, Comparator super T> c, - T[] work, int workBase, int workLen) {
- assert c != null && a != null && lo >= 0 && lo <= hi && hi <= a.length;
-
- int nRemaining = hi - lo;
- if (nRemaining < 2)
- return; // Arrays of size 0 and 1 are always sorted
-
- // If array is small, do a "mini-TimSort" with no merges
- if (nRemaining < MIN_MERGE) {
- int initRunLen = countRunAndMakeAscending(a, lo, hi, c);
- binarySort(a, lo, hi, lo + initRunLen, c);
- return;
- }
参数c是Comparator类型的,又调用了countRunAndMakeAscending()方法
- private static
int countRunAndMakeAscending(T[] a, int lo, int hi, - Comparator super T> c) {
- assert lo < hi;
- int runHi = lo + 1;
- if (runHi == hi)
- return 1;
-
- // Find end of run, and reverse range if descending
- if (c.compare(a[runHi++], a[lo]) < 0) { // Descending
- while (runHi < hi && c.compare(a[runHi], a[runHi - 1]) < 0)
- runHi++;
- reverseRange(a, lo, runHi);
- } else { // Ascending
- while (runHi < hi && c.compare(a[runHi], a[runHi - 1]) >= 0)
- runHi++;
- }
-
- return runHi - lo;
- }
这里调用了compare()方法,并且根据不同条件走不同策略的排序方法。