根据不同的策略,方法执行有不同效果
典型的例子----java中comparator比较器的概念,每次容器排序时,传入我们自己设计好的比较器,会根据比较器来进行排序。
制定比较器接口,里面有一个compare方法
//定义比较器接口
@FunctionalInterface
public interface Comparator<T> {
int compare(T o1, T o2);
default void m() {
System.out.println("m");
}
}
制定实体类
//定义dog类
public class Dog {
int food;
public Dog(int food) {
this.food = food;
}
}
//定义cat类
public class Cat {
int weight, height;
public Cat(int weight, int height) {
this.weight = weight;
this.height = height;
}
}
指定对应的比较器
//cat根据升高大小的比较器
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;
}
}
//cat根据重量大小的比较器
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;
}
}
//dog根据进食量大小的比较器
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 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;
}
}
主函数调用测试
public class Main {
public static void main(String[] args) {
//int[] a = {9, 2, 3, 5, 7, 1, 4};
Cat[] a = {new Cat(3, 3), new Cat(5, 5), new Cat(1, 1)};
//Dog[] a = {new Dog(3), new Dog(5), new Dog(1)};
Sorter<Cat> sorter = new Sorter<>();
sorter.sort(a, new CatWeightComparator());
System.out.println(Arrays.toString(a));
}
}