策略模式屬于對(duì)象的行為模式。其用意是針對(duì)一組算法,將每一個(gè)算法封裝到具有共同接口的獨(dú)立的類(lèi)中,從而使得它們可以相互替換。策略模式使得算法可以在不影響到客戶(hù)端的情況下發(fā)生變化。
策略模式的結(jié)構(gòu)
策略模式是對(duì)算法的包裝,是把使用算法的責(zé)任和算法本身分割開(kāi)來(lái),委派給不同的對(duì)象管理。策略模式通常把一個(gè)系列的算法包裝到一系列的策略類(lèi)里面,作為一個(gè)抽象策略類(lèi)的子類(lèi)。用一句話(huà)來(lái)說(shuō),就是:“準(zhǔn)備一組算法,并將每一個(gè)算法封裝起來(lái),使得它們可以互換”。下面就以一個(gè)示意性的實(shí)現(xiàn)講解策略模式實(shí)例的結(jié)構(gòu)。
這個(gè)模式涉及到三個(gè)角色:
- 環(huán)境(Context)角色:持有一個(gè)Strategy的引用。
- 抽象策略(Strategy)角色:這是一個(gè)抽象角色,通常由一個(gè)接口或抽象類(lèi)實(shí)現(xiàn)。此角色給出所有的具體策略類(lèi)所需的接口。
- 具體策略(ConcreteStrategy)角色:包裝了相關(guān)的算法或行為。
源代碼
環(huán)境角色類(lèi)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
public class Context { //持有一個(gè)具體策略的對(duì)象 private Strategy strategy; /** * 構(gòu)造函數(shù),傳入一個(gè)具體策略對(duì)象 * @param strategy 具體策略對(duì)象 */ public Context(Strategy strategy){ this .strategy = strategy; } /** * 策略方法 */ public void contextInterface(){ strategy.strategyInterface(); } } |
抽象策略類(lèi)
1
2
3
4
5
6
|
public interface Strategy { /** * 策略方法 */ public void strategyInterface(); } |
具體策略類(lèi)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
public class ConcreteStrategyA implements Strategy { @Override public void strategyInterface() { //相關(guān)的業(yè)務(wù) } } public class ConcreteStrategyB implements Strategy { @Override public void strategyInterface() { //相關(guān)的業(yè)務(wù) } } public class ConcreteStrategyC implements Strategy { @Override public void strategyInterface() { //相關(guān)的業(yè)務(wù) } } |
以策略模式分析Java源碼
聲明:這里參考了Java源碼分析-策略模式在Java集合框架實(shí)現(xiàn)代碼中的體現(xiàn)
在java的集合框架中,構(gòu)造Map或者Set時(shí)傳入Comparator比較器,或者創(chuàng)建比較器傳入Collections類(lèi)的靜態(tài)方法中作為方法的參數(shù)為Collection排序時(shí),都使用了策略模式
簡(jiǎn)單的調(diào)用代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
import java.util.*; public class TestComparator { public static void main(String args[]) { LinkedList<String> list = new LinkedList<String>(); list.add( "wangzhengyi" ); list.add( "bululu" ); // 創(chuàng)建一個(gè)逆序比較器 Comparator<String> r = Collections.reverseOrder(); // 通過(guò)逆序比較器進(jìn)行排序 Collections.sort(list, r); System.out.println(list); } } |
使用Collections.reverseOrder()方法實(shí)現(xiàn)一個(gè)比較器后,再調(diào)用Collections.sort(list, r)把比較器傳入該方法中進(jìn)行排序,下面看一下sort(list, r)中的代碼:
1
2
3
4
5
6
7
8
9
|
public static <T> void sort(List<T> list, Comparator<? super T> c) { Object[] a = list.toArray(); Arrays.sort(a, (Comparator)c); ListIterator i = list.listIterator(); for ( int j= 0 ; j<a.length; j++) { i.next(); i.set(a[j]); } } |
Array.sort(a, (Comparator)c);這句繼續(xù)把比較器傳入處理,下面是Array.sort(a, (Comparator)c)的具體操作:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
public static <T> void sort(T[] a, Comparator<? super T> c) { if (LegacyMergeSort.userRequested) legacyMergeSort(a, c); else TimSort.sort(a, c); } static <T> void sort(T[] a, Comparator<? super T> c) { sort(a, 0 , a.length, c); } /** To be removed in a future release. */ private static <T> void legacyMergeSort(T[] a, Comparator<? super T> c) { T[] aux = a.clone(); if (c== null ) mergeSort(aux, a, 0 , a.length, 0 ); else mergeSort(aux, a, 0 , a.length, 0 , c); } |
繼續(xù)跟下去好了:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
private static void mergeSort(Object[] src, Object[] dest, int low, int high, int off, Comparator c) { int length = high - low; // Insertion sort on smallest arrays if (length < INSERTIONSORT_THRESHOLD) { for ( int i=low; i<high; i++) for ( int j=i; j>low && c.compare(dest[j- 1 ], dest[j])> 0 ; j--) swap(dest, j, j- 1 ); return ; } // Recursively sort halves of dest into src int destLow = low; int destHigh = high; low += off; high += off; int mid = (low + high) >>> 1 ; mergeSort(dest, src, low, mid, -off, c); mergeSort(dest, src, mid, high, -off, c); // If list is already sorted, just copy from src to dest. This is an // optimization that results in faster sorts for nearly ordered lists. if (c.compare(src[mid- 1 ], src[mid]) <= 0 ) { System.arraycopy(src, low, dest, destLow, length); return ; } // Merge sorted halves (now in src) into dest for ( int i = destLow, p = low, q = mid; i < destHigh; i++) { if (q >= high || p < mid && c.compare(src[p], src[q]) <= 0 ) dest[i] = src[p++]; else dest[i] = src[q++]; } } |
把使用到比較器的代碼挑選出來(lái):
1
2
3
4
5
6
|
// If list is already sorted, just copy from src to dest. This is an // optimization that results in faster sorts for nearly ordered lists. if (c.compare(src[mid- 1 ], src[mid]) <= 0 ) { System.arraycopy(src, low, dest, destLow, length); return ; } |
這里的compare方法在Comparator接口中也有定義:
1
2
3
|
public interface Comparator<T> { int compare(T o1, T o2); } |
由于這里是泛型實(shí)現(xiàn)了Comparator,所以實(shí)際執(zhí)行時(shí),會(huì)根據(jù)比較器的具體實(shí)現(xiàn)類(lèi)調(diào)用到實(shí)現(xiàn)代碼,也就是上面創(chuàng)建的逆序比較器的compare方法,其實(shí)現(xiàn)方法如下:
1
2
3
|
public int compare(Comparable<Object> c1, Comparable<Object> c2) { return c2.compareTo(c1); } |