一、参考资料
- Java 官方文档
- Java中使用到的策略模式
Comparator、comparable
二、主要设计思想
三、应用场景
1、Cat.java 对象
/**
* @description: 猫对象
* @author: flygo
* @time: 2022/7/4 11:11
*/
public class Cat {
private int height, weight;
public Cat() {}
public Cat(int weight, int height) {
this.weight = weight;
this.height = height;
}
public int compareTo(Cat c) {
if (this.weight < c.weight) return -1;
else if (this.weight > c.weight) return 1;
else return 0;
}
@Override
public String toString() {
return "Cat{" + "height=" + height + ", weight=" + weight + '}';
}
}
2、Sorter.java 排序类
/**
* @description: 排序对象
* @author: flygo
* @time: 2022/7/4 11:16
*/
public class Sorter {
public void sort(Cat[] arr) {
for (int i = 0; i < arr.length - 1; 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);
}
}
static void swap(Cat[] arr, int i, int j) {
Cat temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
3、StrategyMain 主类
import java.util.Arrays;
/**
* @description: 主方法
* @author: flygo
* @time: 2022/7/4 11:15
*/
public class StrategyMain {
public static void main(String[] args) {
// int[] arr = {2, 4, 3, 6, 10, 1};
Cat[] arr = {new Cat(3, 3), new Cat(5, 5), new Cat(1, 1)};
Sorter sorter = new Sorter();
sorter.sort(arr);
System.out.println(Arrays.toString(arr));
}
}
四、使用泛型调整修改
1、定义Comparable接口
/**
* @description: 比较接口类
* @author: flygo
* @time: 2022/7/4 15:46
*/
public interface Comparable<T> {
int compareTo(T o);
}
2、Sorter 排序类
/**
* @description: 排序对象
* @author: flygo
* @time: 2022/7/4 11:16
*/
public class Sorter {
public void sort(Comparable[] arr) {
for (int i = 0; i < arr.length - 1; 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);
}
}
static void swap(Comparable[] arr, int i, int j) {
Comparable temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
3、定义一个需要排序的对象,如Dog
/**
* @description: 狗
* @author: flygo
* @time: 2022/7/4 15:48
*/
public class Dog implements Comparable<Dog> {
int food;
public Dog(int food) {
this.food = food;
}
@Override
public int compareTo(Dog o) {
if (this.food < o.food) return -1;
else if (this.food > o.food) return 1;
else return 0;
}
@Override
public String toString() {
return "Dog{" + "food=" + food + '}';
}
}
4、最终效果
import java.util.Arrays;
/**
* @description: 主方法
* @author: flygo
* @time: 2022/7/4 11:15
*/
public class StrategyMain {
public static void main(String[] args) {
// int[] arr = {2, 4, 3, 6, 10, 1};
// Cat[] arr = {new Cat(3, 3), new Cat(5, 5), new Cat(1, 1)};
Dog[] arr = {new Dog(5), new Dog(1), new Dog(3)};
Sorter sorter = new Sorter();
sorter.sort(arr);
System.out.println(Arrays.toString(arr));
}
}
五、源码地址