策略模式
1. 使用场景
运行期间可以动态替换不同的算法实现
2. 实现举例
JDK提供了最优秀的排序算法,但排序的规则(策略)不能够写死在JDK中,需要提供包含了不同业务规则的比较器实现,每一个Comparator实现对应一种比较规则(策略)
Collections.sort(list, comparator);
Arrays.sort(array, comparator);
这里Comparator接口体现了对要排序的集合应用不同的比较策略
@FunctionalInterface
public interface Comparator<T> {
int compare(T o1, T o2);
}
返回负数表示o1小于o2,返回正数表示o1大于o2,返回零表示o1等于o2.
class Student {
int id;
String name;
int age;
public Student(int id, String name, int age) {
super();
this.id = id;
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
public static void main(String[] args) {
List<Student> list = Arrays.asList(
new Student(1, "Tom", 18),
new Student(2, "Jerry", 16),
new Student(3, "Smith", 15)
);
// 按年龄比较:小在前,大在后
Collections.sort(list, new Comparator<Student>(){
@Override
public int compare(Student o1, Student o2) {
return o1.age - o2.age;
}
});
System.out.println(list);
// 按姓名比较:小在前,大在后
Collections.sort(list, new Comparator<Student>(){
@Override
public int compare(Student o1, Student o2) {
return o1.name.compareTo(o2.name);
}
});
System.out.println(list);
// 按id比较:小在前,大在后
Collections.sort(list, new Comparator<Student>(){
@Override
public int compare(Student o1, Student o2) {
return o1.id - o2.id;
}
});
System.out.println(list);
}