统一接口
public interface SortorFace<T> {
T sort(T t);
}
策略控制
/**
* 策略控制器
*/
public class Sortor<T> {
private SortorFace<T> sortorFace;
public Sortor(SortorFace<T> sortorFace) {
this.sortorFace = sortorFace;
}
public T sort(T t) {
T sort = sortorFace.sort(t);
return sort;
}
}
int数组排序
public class IntSortor implements SortorFace<int[]>{
@Override
public int[] sort(int[] ints) {
Arrays.sort(ints);
return ints;
}
}
@Data
public class Man {
private int hight;
private double weight;
public Man(int hight, double weight) {
this.hight = hight;
this.weight = weight;
}
}
public class ManSortor implements SortorFace<Man[]>{
@Override
public Man[] sort(Man[] man) {
Arrays.sort(man,(Comparator.comparingInt(Man::getHight)));
return man;
}
}
@Test
void test(){
int[] a=new int[]{1,5,6,4,9,7};
Sortor<int[]> sortor = new Sortor(new IntSortor());
int[] sort = sortor.sort(a);
System.out.println(Arrays.toString(sort));
Man[] mans=new Man[]{new Man(20,20),new Man(10,10),new Man(15,15)};
Sortor<Man[]> sortorMan = new Sortor(new ManSortor());
Man[] sortMan = sortorMan.sort(mans);
System.out.println(Arrays.toString(sortMan));
}
总结:
1.定义:一系列的算法,把它们一个个封装起来, 并且使它们可相互替换。
2.实现算法与业务解耦
3.策略模式重心不在算法实现,在如何组织,调用算法,实现算法与业务解耦。比如多个if-else的结构