詳解Java編程中的策略模式
策略模式屬于對象的行為模式。其用意是針對一組算法,將每一個算法封裝到具有共同接口的獨立的類中,從而使得它們可以相互替換。策略模式使得算法可以在不影響到客戶端的情況下發(fā)生變化。
策略模式的結(jié)構(gòu)
策略模式是對算法的包裝,是把使用算法的責任和算法本身分割開來,委派給不同的對象管理。策略模式通常把一個系列的算法包裝到一系列的策略類里面,作為一個抽象策略類的子類。用一句話來說,就是:“準備一組算法,并將每一個算法封裝起來,使得它們可以互換”。下面就以一個示意性的實現(xiàn)講解策略模式實例的結(jié)構(gòu)。

這個模式涉及到三個角色:
- 環(huán)境(Context)角色:持有一個Strategy的引用。
- 抽象策略(Strategy)角色:這是一個抽象角色,通常由一個接口或抽象類實現(xiàn)。此角色給出所有的具體策略類所需的接口。
- 具體策略(ConcreteStrategy)角色:包裝了相關(guān)的算法或行為。
源代碼
環(huán)境角色類
public class Context {
//持有一個具體策略的對象
private Strategy strategy;
/**
* 構(gòu)造函數(shù),傳入一個具體策略對象
* @param strategy 具體策略對象
*/
public Context(Strategy strategy){
this.strategy = strategy;
}
/**
* 策略方法
*/
public void contextInterface(){
strategy.strategyInterface();
}
}
抽象策略類
public interface Strategy {
/**
* 策略方法
*/
public void strategyInterface();
}
具體策略類
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集合框架實現(xiàn)代碼中的體現(xiàn)
在java的集合框架中,構(gòu)造Map或者Set時傳入Comparator比較器,或者創(chuàng)建比較器傳入Collections類的靜態(tài)方法中作為方法的參數(shù)為Collection排序時,都使用了策略模式
簡單的調(diào)用代碼:
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)建一個逆序比較器
Comparator<String> r = Collections.reverseOrder();
// 通過逆序比較器進行排序
Collections.sort(list, r);
System.out.println(list);
}
}
使用Collections.reverseOrder()方法實現(xiàn)一個比較器后,再調(diào)用Collections.sort(list, r)把比較器傳入該方法中進行排序,下面看一下sort(list, r)中的代碼:
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)的具體操作:
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ù)跟下去好了:
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++];
}
}
把使用到比較器的代碼挑選出來:
// 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接口中也有定義:
public interface Comparator<T> {
int compare(T o1, T o2);
}
由于這里是泛型實現(xiàn)了Comparator,所以實際執(zhí)行時,會根據(jù)比較器的具體實現(xiàn)類調(diào)用到實現(xiàn)代碼,也就是上面創(chuàng)建的逆序比較器的compare方法,其實現(xiàn)方法如下:
public int compare(Comparable<Object> c1, Comparable<Object> c2) {
return c2.compareTo(c1);
}
相關(guān)文章
Java異步調(diào)用轉(zhuǎn)同步方法實例詳解
這篇文章主要介紹了Java異步調(diào)用轉(zhuǎn)同步方法實例詳解,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-06-06
Activiti7通過代碼動態(tài)生成工作流實現(xiàn)詳解
這篇文章主要為大家介紹了Activiti7通過代碼動態(tài)生成工作流實現(xiàn)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-11-11
Java多線程之 FutureTask:帶有返回值的函數(shù)定義和調(diào)用方式
這篇文章主要介紹了Java多線程之 FutureTask:帶有返回值的函數(shù)定義和調(diào)用方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-07-07
Java版數(shù)據(jù)結(jié)構(gòu)插入數(shù)據(jù)時遇到的結(jié)點為空的問題詳解
這篇文章主要介紹了Java版數(shù)據(jù)結(jié)構(gòu)插入數(shù)據(jù)時遇到的結(jié)點為空的問題及解決辦法,需要的朋友們可以學(xué)習(xí)下。2019-09-09
Java 實戰(zhàn)項目錘煉之醫(yī)院門診收費管理系統(tǒng)的實現(xiàn)流程
讀萬卷書不如行萬里路,只學(xué)書上的理論是遠遠不夠的,只有在實戰(zhàn)中才能獲得能力的提升,本篇文章手把手帶你用java+html+jdbc+mysql實現(xiàn)一個醫(yī)院門診收費管理系統(tǒng),大家可以在過程中查缺補漏,提升水平2021-11-11
idea安裝jerbel及文件上傳下載的實現(xiàn)示例
JRebel是一個Java開發(fā)工具,它是一款用于實時代碼重載的插件,本文主要介紹了idea安裝jerbel及文件上傳下載的實現(xiàn)示例,具有一定的參考價值,感興趣的可以了解下2023-09-09

