ps:在以下讲述策略模式中,模仿的场景如下:有一个Dog类,它有两个属性height和weight。现在想利用Sorter类,既可以通过比较height来对Dog进行排序,又可以按照weight对Dog进行排序。类图和代码如下。
1、Comparator接口(不同于Java 类库中的Comparator接口)
public interface Comparator<T> {
//任何实现Comparator接口的类,都必须实现compare方法
int compare(T o1,T o2);
}
2、DogHeightComparator类
public class DogHeightComparator implements Comparator<Dog>{
@Override
public int compare(Dog o1, Dog o2) {
if (o1.getHeight()<o2.getHeight()) {return -1;}
else if (o1.getHeight()>o2.getHeight()) {return 1;}
return 0;
}
}
3、DogWeightComparator类
public class DogWeightComparator implements Comparator<Dog>{
@Override
public int compare(Dog o1, Dog o2) {
if (o1.getWeight()<o2.getWeight()) {return -1;}
else if (o1.getWeight()>o2.getWeight()) {return 1;}
return 0;
}
}
4、Dog类
public class Dog{
private int height;
private int weight;
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public Dog(int height, int weight){
this.height = height;
this.weight = weight;
}
@Override
public String toString() {
return "Dog{" +
"height=" + height +
", weight=" + weight +
'}';
}
}
5、Sorter类
public class Sorter<T> {
//使用选择排序,对传进来的数组进行排序
public void selectSort(T[] arr, Comparator<T> comparator){
for (int i = 0; i < arr.length; i++) {
int minIndex = i;
for (int j = i+1; j < arr.length; j++) {
//使用comparator中的compare方法提供的比较策略来进行大小比较
if (comparator.compare(arr[j],arr[minIndex])==-1){
minIndex = j;
}
}
swap(arr,i,minIndex);
}
}
//交换值
public void swap(T[] arr, int i, int minIndex) {
T temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
6、Main类(测试)
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
Dog[] cats ={new Dog(3,5),new Dog(1,1),new Dog(5,3)};
Sorter<Dog> sorter = new Sorter<>();
//使用比较身高来排序的策略
/* sorter.selectSort(cats,new DogHeightComparator());*/
//使用比较体重来排序的策略
sorter.selectSort(cats,new DogWeightComparator());
System.out.println(Arrays.toString(cats));
}
}
总结:使用策略模式,在提供不同的比较策略的情况下,最终在不改变Sorter类中的排序方法的情况下,最终改变排序规则。