策略模式定义:封装做一件事情的不同实现方式
下面是实现一个排序器的代码:
策略模式:使用Comparator
1、定义一个排序器
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);
}
}
//sort(int)
void swap(T[] arr, int i, int j) {
T temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
2、定义需要比较的对象
public class Cat implements Comparable<Cat> {
int weight, height;
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{" +
"weight=" + weight +
", height=" + height +
'}';
}
}
3、定义对象比较策略1
public class CatHeightComparator implements Comparator<Cat> {
@Override
public int compare(Cat o1, Cat o2) {
if(o1.height > o2.height) return -1;
else if (o1.height < o2.height) return 1;
else return 0;
}
}
4、定义对象比较策略2
public class CatWeightComparator implements Comparator<Cat> {
@Override
public int compare(Cat o1, Cat o2) {
if(o1.weight < o2.weight) return -1;
else if (o1.weight > o2.weight) return 1;
else return 0;
}
}
5、测试类
public class Main {
public static void main(String[] args) {
Cat[] a = {new Cat(2, 2), new Cat(5, 5), new Cat(1, 1)};
Sorter<Cat> sorter = new Sorter<>();
sorter.sort(a, new CatWeightComparator());
//拉姆达表达是写法
sorter.sort(a, (o1, o2)->{
if(o1.weight < o2.weight) return -1;
else if (o1.weight>o2.weight) return 1;
else return 0;
});
System.out.println(Arrays.toString(a));
}
}
总结:
设计模式中心思想:对修改关闭,对扩展开放
常见使用场景:抽奖算发、随机数生成算法、游戏英雄的技能