2策略模式
简介:策略模式(Strategy Pattern),一个类的行为或其算法可以在运行时更改。这种类型的设计模式属于行为型模式。
定义一系列算法,将每一个算法封装起来,并让它们可以相互替换。策略模式让算法独立于使用它的客户而变化,也称为政策模式(Policy)。
意图:策略模式只要是为了对一系列算法的封装,客户端自己决定自己使用什么策略进行后续的计算,策略本身不做决定使用何种算法,算法的选择由客户端自己决定。理论上客户端只需要觉得自己采取哪种策略,后续功能就会根据策略结果改变,而不需要改动后续内容。
应用实例:旅行的出游方式,选择骑自行车、坐汽车,每一种旅行方式都是一个策略
场景:
一个排序方法,需要对不同的对象进行排序,并且排序的规则根据采用的不同策略,结果也不同。
排序方法:
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);
}
}
private void swap(T[] arr, int i, int j) {
T temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
策略接口:(模拟java本身的接口)
/**
* 比较器
* @param <T>
*/
public interface Comparator<T> {
int compare(T o1, T o2);
}
策略实现:
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;
}
}
}
2、猫根据体重排序策略
public class CatWidthComparator implements Comparator<Cat> {
@Override
public int compare(Cat o1, Cat o2) {
if(o1.width < o2.width) {
return -1;
} else if(o1.width > o2.width) {
return 1;
} else {
return 0;
}
}
}
3 、狗 根据饭量排序策略
public class DogComparator implements Comparator<Dog> {
@Override
public int compare(Dog o1, Dog o2) {
if(o1.food < o2.food) {
return -1;
} else if(o1.food > o2.food) {
return 1;
} else {
return 0;
}
}
}
实体bean
public class Dog implements Comparable<Dog> {
int food;
public Dog(int food) {
this.food = food;
}
@Override
public int compareTo(Dog d) {
if(d.food > this.food) {
return -1;
} else if(d.food < this.food) {
return 1;
} else {
return 0;
}
}
@Override
public String toString() {
return "Dog{" +
"food=" + food +
'}';
}
}
public class Cat implements Comparable<Cat>{
int width;
int height;
public Cat(int width, int height) {
this.width = width;
this.height = height;
}
@Override
public int compareTo(Cat c){
if(c.width > this.width) {
return -1;
} else if (c.width < this.width) {
return 1;
} else {
return 0;
}
}
@Override
public String toString() {
return "Cat{" +
"width=" + width +
", height=" + height +
'}';
}
}
Main 测试排序
public class Main {
public static void main(String[] args) {
//int[] arr = [0,6,3,7,9];
// int[] arr = {0,6,3,7,9};
Cat c1 = new Cat(1,6);
Cat c2 = new Cat(2,2);
Cat c3 = new Cat(3,3);
Cat[] c = new Cat[3];
c[0] = c1;
c[1] = c2;
c[2] = c3;
/* Dog d = new Dog(7);
Dog d1 = new Dog(2);
Dog d2 = new Dog(4);
Dog[] dArr = new Dog[3];
dArr[0] = d;
dArr[1] = d1;
dArr[2] = d2;*/
Sorter<Cat> s = new Sorter<Cat>();
//s.sort(c,new CatHeightComparator());
s.sort(c,new CatWidthComparator());
/*s.sort(c,(o1,o2)->{
if(o1.width > o2 .width) return -1;
else if(o1.width < o2.width) return 1;
return 0;
});*/
System.out.println(Arrays.toString(c));
}
}
当客户端选择不同的 策略时 排序方法的比较规则 会改变为策略的比较规则,从而达到只改变客户端代码,完成算法的切换。
特此说明:以上内容学自马士兵马老师课堂内容,本人只是做为学习记录。