一、简要描述
- Java 官方文档
- Java中使用到的策略模式
Comparator、comparable
二、主要设计思想
三、重新调整修改
1、定义支持泛型的Comparator比较器
/**
* @description: 比较器接口
* @author: flygo
* @time: 2022/7/4 16:26
*/
public interface Comparator<T> {
int compare(T o1, T o2);
}
2、调整Sorter排序类和方法
/**
* @description: 排序对象
* @author: flygo
* @time: 2022/7/4 11:16
*/
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);
}
}
void swap(T[] arr, int i, int j) {
T temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
3、定义猫高度的比较器
/**
* @description: 猫按高比较
* @author: flygo
* @time: 2022/7/4 16:29
*/
public class CatHeightComparator implements Comparator<Cat> {
@Override
public int compare(Cat o1, Cat o2) {
if (o1.getHeight() < o2.getHeight()) return -1;
else if (o1.getHeight() > o2.getHeight()) return 1;
else return 0;
}
}
4、定义猫重量的比较器
/**
* @description: 猫按体重比较
* @author: flygo
* @time: 2022/7/4 16:29
*/
public class CatWeightComparator implements Comparator<Cat> {
@Override
public int compare(Cat o1, Cat o2) {
if (o1.getWeight() > o2.getWeight()) return -1;
else if (o1.getWeight() < o2.getWeight()) return 1;
else return 0;
}
}
5、主方法实现排序
import java.util.Arrays;
/**
* @description: 主方法
* @author: flygo
* @time: 2022/7/4 11:15
*/
public class StrategyMain {
public static void main(String[] args) {
Cat[] arr = {new Cat(3, 3), new Cat(5, 5), new Cat(1, 1)};
Sorter sorter = new Sorter();
// CatHeightComparator comparator = new CatHeightComparator();
CatWeightComparator comparator = new CatWeightComparator();
sorter.sort(arr, comparator);
System.out.println(Arrays.toString(arr));
}
}
四、Lambda表达式写法
1、Comparator 接口定义为 @FunctionalInterface
/**
* @description: 比较器接口
* @author: flygo
* @time: 2022/7/4 16:26
*/
@FunctionalInterface
public interface Comparator<T> {
int compare(T o1, T o2);
}
2、Lambda表达式调用方式
import java.util.Arrays;
/**
* @description: 主方法
* @author: flygo
* @time: 2022/7/4 11:15
*/
public class StrategyMain {
public static void main(String[] args) {
method2();
}
private static void method2() {
Cat[] arr = {new Cat(3, 3), new Cat(5, 5), new Cat(1, 1)};
Sorter<Cat> sorter = new Sorter();
// CatHeightComparator comparator = new CatHeightComparator();
CatWeightComparator comparator = new CatWeightComparator();
sorter.sort(
arr,
(o1, o2) -> {
if (o1.getHeight() < o2.getHeight()) return -1;
else if (o1.getHeight() > o2.getHeight()) return 1;
else return 0;
});
System.out.println(Arrays.toString(arr));
}
}