首先我们看下Comparable,基本的排序 首先定义一个排序的接口,任何一个想排序的类需要实现此接口
public interface Comparable<T> {
int compareTo(T t);
}
举个类:
import java.util.Objects;
public class Dog implements Comparable<Dog>{
private int height;
private int weight;
public Dog(int height, int weight) {
this.height = height;
this.weight = 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;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Dog dog = (Dog) o;
return height == dog.height &&
weight == dog.weight;
}
@Override
public int hashCode() {
return Objects.hash(height, weight);
}
@Override
public String toString() {
return "Dog{" +
"height=" + height +
", weight=" + weight +
'}';
}
/*
* 比较方法,但是我想在不同场景下使用不同的2比较策略,这个就不够灵活了,要使用策略模式
*/
@Override
public int compareTo(Dog dog) {
return this.height - dog.height < 0 ? -1 : 1;
}
}
然后我们再定义一个排序类:
public class Sorter {
//对实现Comparable的类的数组进行排序
public static void sort(Comparable[] arr){
for (int i = 0; i < arr.length; i++) {
int minPos = i;
for(int j=i+1;j<arr.length;j++){
minPos = arr[j].compareTo(arr[minPos]) == -1 ? j:minPos;
}
swap(arr,i,minPos);
}
}
private static void swap(Comparable[] arr, int i, int j) {
Comparable temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
这样确实是可以在类的方法中实现比较逻辑,但是我想下次按Dog类的weight属性来排序怎么办?所以我们得有不同的策略。
策略模式:
首先定义一个策略接口,比较器
public interface MyComparator<T> {
int comparaTo(T t1,T t2);
}
然后定义一个排序类:
public class MySorter<T> {
//对实现Comparable的类的数组进行排序
public void sort(T[] arr,MyComparator<T> myComparator){
for (int i = 0; i < arr.length; i++) {
int minPos = i;
for(int j=i+1;j<arr.length;j++){
minPos = myComparator.comparaTo(arr[j],arr[minPos]) >0 ? j:minPos;
}
swap(arr,i,minPos);
}
}
private void swap(T[] arr, int i, int j) {
T temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
使用比较器来排序:
public class Test1 {
public static void main(String[] args) {
Dog[] dogs = {new Dog(5,5),new Dog(1,1),new Dog(3,3)};
Dog[] dogs1 = {new Dog(5,5),new Dog(1,1),new Dog(3,3)};
MySorter<Dog> dogMySorter = new MySorter<>();
//这样就可以传入不同的比较器策略了
dogMySorter.sort(dogs,(Dog d1,Dog d2)->{
return d1.getHeight() - d2.getHeight();
});
dogMySorter.sort(dogs1,(Dog d1,Dog d2)->{
return -d1.getHeight() + d2.getHeight();
});
System.out.println("Arrays.toString(dogs) = " + Arrays.toString(dogs));
System.out.println("Arrays.toString(dogs) = " + Arrays.toString(dogs1));
}
}
java的Comparator用到了策略模式