目錄
Intent
定義一系列算法,封裝每個算法,並使它們可以互換。
策略模式可以讓算法獨立於使用它的客戶端。
Class Diagram
- Strategy 接口定義了一個算法族,它們都實現了 behavior() 方法。
- Context 是使用到該算法族的類,其中的 doSomething() 方法會調用 behavior(),setStrategy(Strategy) 方法可以動態地改變 strategy 對象,也就是說能動態地改變 Context 所使用的算法。
Implementation
Comparator
package com.strategy;
/**
* 函數式接口
*/
@FunctionalInterface
public interface Comparator<T> {
int compare(T o1, T o2);
// java1.8後特性
default void m() {
System.out.println("m");
}
}
Sorter
package com.strategy;
public class Sorter<T> {
public void sort(T[] arr, Comparator<T> comparator) {
for(int i=0; i<arr.length - 1; i++) {
int minPos = i;
for(int j=i+1; j<arr.length; j++) {
minPos = comparator.compare(arr[j],arr[minPos])==-1 ? j : minPos;
}
swap(arr, i, minPos);
}
}
//sort(int)
void swap(T[] arr, int i, int j) {
T temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
Main
package com.strategy;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
//int[] a = {9, 2, 3, 5, 7, 1, 4};
Dog[] dogs = {new Dog(3), new Dog(5), new Dog(1)};
Sorter<Dog> sorter1 = new Sorter<>();
sorter1.sort(dogs, new DogComparator());
Cat[] cats = {new Cat(3, 3), new Cat(5, 5), new Cat(1, 1)};
Sorter<Cat> sorter2 = new Sorter<>();
sorter2.sort(cats, new CatHeightComparator());
sorter2.sort(cats, new CatWeightComparator());
sorter2.sort(cats, (o1, o2)->{
if(o1.weight < o2.weight) return -1;
else if (o1.weight>o2.weight) return 1;
else return 0;
});
System.out.println(Arrays.toString(cats));
}
}
CatWeightComparator
package com.strategy;
public class CatWeightComparator implements Comparator<Cat> {
@Override
public int compare(Cat o1, Cat o2) {
if(o1.weight < o2.weight) return -1;
else if (o1.weight > o2.weight) return 1;
else return 0;
}
}
CatHeightComparator
package com.strategy;
public class CatHeightComparator implements Comparator<Cat> {
@Override
public int compare(Cat o1, Cat o2) {
if(o1.height > o2.height) return -1;
else if (o1.height < o2.height) return 1;
else return 0;
}
}
DogComparator
package com.strategy;
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;
}
}