策略模式:定义一组算法,将每个算法都封装起来,并且使他们之间可以互换
简单点理解为定义公共方法,调用公共方法
public class Person {
private int age;
private int num;
public Person(int age, int name) {
this.age = age;
this.num = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getNum() {
return num;
}
public void setNum(int name) {
this.num = name;
}
}
//定义公共方法
@FunctionalInterface
public interface Comparator<T> {
int compareTo(T o1,T o2);
}
//调用时使用接口
public class Sorter<T> {
public void sort(T[] arr, Comparator<T> comparator) {
//冒泡排序
for (int i = 0; i < arr.length - 1; i++) {
int pos = i;
for (int j = i + 1; j < arr.length; j++) {
pos = comparator.compareTo(arr[j], arr[pos]) == -1 ? j : pos;
}
swap(arr, i, pos);
}
}
void swap(T[] arr, int i, int j) {
T temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
//main方法,对于不同策略只需要实现comparator接口就行
public class Main {
public static void main(String[] args) {
Person[] arr = {new Person(20, 3), new Person(19, 1), new Person(21, 2)};
Sorter<Person> sorter = new Sorter<>();
//按年龄排序
sorter.sort(arr, (o1, o2) -> {
if (o1.getAge() > o2.getAge()) {
return 1;
} else if (o1.getAge() < o2.getAge()) {
return -1;
} else {
return 0;
}
});
//按num排序
sorter.sort(arr, (o1, o2) -> {
if (o1.getNum() > o2.getNum()) {
return 1;
} else if (o1.getNum() < o2.getNum()) {
return -1;
} else {
return 0;
}
});
//由此可见,策略模式可以随意扩展,只要实现对应接口就行
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。