定義
策略模式定義了一系列的算法,並將每一個算法封裝起來,而且使它們還可以相互替換。策略模式讓算法獨立於使用它的客戶而獨立變化。
舉個栗子
你想比較小狗的體重、小狗的飯量,小狗的身高。這就是你的策略,可以隨意切換。
再舉個栗子
Comparator(java.util)就是用典型的策略模式。實現Comparator接口的類必然就會實現一個compareTo(Object o1, Object o2)的方法,而這個方法就是算法中的一部分,所有使用了compareTo方法的類都不會關心compareTo是如何工作的,只關心他的返回值,這也是面向對象中著名的封裝特性。
上示例代碼
public interface Comparator<T> {
/**
* o1<o2 return -1
* o1==o2 return 0
* o1>o2 return 正數
* @param o1
* @param o2
* @return
*/
int compare(T o1,T o2);
}
比較小狗誰喫的多
public class DogComparator implements Comparator<Dog> {
@Override
public int compare(Dog o1, Dog o2) {
if(o1.food < o2.food){
return -1;
}else if(o1.food > o2.food){
return 1;
}else {
return 0;
}
}
}
比較算法(選擇排序)
public class Sorter<T> {
public void sort(T[] arr,Comparator<T> comparator) {
for (int i =0;i<arr.length-1;i++){
int minIndex = i;
for (int j =i+1;j<arr.length;j++) {
minIndex = comparator.compare(arr[j] ,arr[minIndex]) == -1? j : minIndex;
}
swap(i,minIndex,arr);
}
}
private void swap(int i, int minIndex,T[] arr) {
T temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
測試類
public class Main {
public static void main(String[] args) {
// int[] a= {9,2,3,5,7,1,4};
// Cat[] a ={new Cat(1,1),new Cat(2,2)};
// Sorter<Cat> sorterCat = new Sorter<Cat>();
Dog[] d = {new Dog(3),new Dog(5),new Dog(10)};
Sorter<Dog> sorter = new Sorter<Dog>();
// ====Dog的排序===
sorter.sort(d, new DogComparator());
System.out.println("Dog:"+Arrays.toString(d));
// ====Cat的排序===
// sorterCat.sort(a,new CatHeightComparator());
// System.out.println("Cat:"+Arrays.toString(a));
}
}
輸出