策略模式
比较器接口
public interface Comparator<T> {
int compare(T o1, T o2);
}
sort方法
public class Sorter<T> {
public void sort(T[] arr, Comparator<T> comparator) {
for (int i = 0; i < arr.length; i++) {
int minPos = i;
for (int j = i; j < arr.length; j++)
if (comparator.compare(arr[j], arr[minPos]) < 0)
minPos = j;
if (minPos != i)
swap(arr, minPos, i);
}
}
private void swap(T[] arr, int i, int j) {
T temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
Dog实体类
public class Dog {
int food;
public Dog(int food) {
this.food = food;
}
@Override
public String toString() {
return "Dog{" +
"food=" + food +
'}';
}
}
Client和Comparator
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
Dog[] dogs = {new Dog(8), new Dog(4)};
(new Sorter<Dog>()).sort(dogs, (o1, o2) -> o1.food - o2.food);
System.out.println(Arrays.toString(dogs));
}
}
跟上面的内容无关
@FunctionalInterface
public interface Comparator<T> {
int compare(T o1, T o2);
// 类里面增加了Default方法,用于lambda表达式
default void m() { // 实现这个接口的类可以不实现m方法,只用实现Compare
}
}
JDK 1.8以后,interface可以定义默认方法。