策略模式就是通过分别封装行为接口,实现算法族,超类里放行为接口对象,在子类里具体设定行为对象。
原则就是:分离变化部分,封装接口,基于接口编程各种功能。此模式让行为的变化独立于算法的使用者。
策略模式就是将算法与业务隔离开来,方便我们根据实际情况来做出调整的模式。
主要接口
- Comparator
举例
现有Dog 类,有两大属性,高度和重量。
public class Dog {
int height;
int weight;
public Dog(int height, int weight) {
this.height = height;
this.weight = weight;
}
@Override
public String toString() {
return "Dog{" +
"height=" + height +
", weight=" + weight +
'}';
}
}
我们想要按照狗的高度来给狗进行排序。代码如下
public class Main {
public static void main(String[] args) {
Dog[] arr = {new Dog(3,3),new Dog(1,1),new Dog(5,5)}; // 待排序数组
Sorter sorter = new Sorter();// 自定义的比较类
arr = (Dog[]) sorter.sort(arr,((o1, o2) -> { // 重点在这里,自定义了狗的比较方式。
Dog dog1 = (Dog) o1;
Dog dog2 = (Dog) o2;
if (dog1.height - dog2.height<0) return -1;
else if (dog1.height - dog2.height>0) return 1;
else return 0;
}));
System.out.println(Arrays.toString(arr));
}
}
public class Sorter<T> {
// 排序方法
public T[] sort(T[] arr, Comparator<T> comparator) {
if (arr == null || arr.length == 0)
return arr;
for (int i = 1; i < arr.length; i++) {// 假设第一个数的位置是正确的,要想往后移,就必须要假设第一个数的位置是正确的。
int j = i;
T target = arr[i];// 等待插入数字
// 后移数字
while (j > 0 && comparator.compare(target , arr[j - 1])==-1) {
arr[j] = arr[j - 1];
j--;
}
// 插入数字
arr[j] = target;
}
return arr;
}
}
如此一来,假定我们想要修改狗的排序方式为重量,那么只需要修改comparator里面的方法,也就是不同情况不容策略。