策略模式

策略模式

理解:
1. 策略接口定义策略实现类的规范(一般策略接口内部方法定义泛型参数提高代码的灵活性);
2. 多个策略实现类实现策略接口,编写各自的具体的策略方法实现;
3. 策略调用类,一般会通过两种方式来调用不同的策略实现,第一种方式是策略调用类内聚策略接口属性,在具体的方法中赋值为具体的策略实现;第二种就是通过调用方法传参,调用方法加上策略接口参数,具体使用哪种策略实现通过传参实现;

1
2
3
4
5
6
7
8
9
// 策略接口
@FunctionalInterface
public interface Comparator<T> {
int compare(T o1, T o2);

default void m() {
System.out.println("m");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// 具体的策略接口实现
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;
}
}

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;
}
}

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;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// 策略调用类
public class Sorter<T> {

// 内聚策略接口属性
private Comparator myComparator;

// 通过内聚策略接口形式实现策略调用
public void sort1(T[] arr) {
if (arr[0] instanceof Cat) {
myComparator = new CatWeightComparator();
} else {
myComparator = new DogComparator();
}
for(int i=0; i<arr.length - 1; i++) {
int minPos = i;

for(int j=i+1; j<arr.length; j++) {
minPos = myComparator.compare(arr[j],arr[minPos])==-1 ? j : minPos;
}
swap(arr, i, minPos);
}
}

// 通过传参形式实现策略调用
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);
}
}

void swap(T[] arr, int i, int j) {
T temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}