基本介绍
策略模式中,定义算法族,分别封装起来,让他们之间可以相互替换,此模式让算法的变化独立于使用算法的客户;
算法体现了几个设计原则
- 把变化的代码从不变的代码中分离出来;
- 针对接口编程而不是具体类(定义了策略接口)
- 多用组合/聚合,少用继承(客户通过组合方式使用策略)
类图
说明:从上图可以看到,context有成员变量strategy或者其他的策略接口,需要使用到哪个策略,可以在构造器中指定
例子
/**
* 策略模式
*/
public class StrategyDemo {
public static void main(String[] args) {
Integer[] a = {2,5,3,7,6,9,8};
/**
* 说明
* 1.实现了Comparator接口(策略接口),匿名类 对象new Comparator<Integer>()
* 2.对象new Comparator<Integer>() {。。}就是实现了策略接口的对象
* 3.public int compare(Integer o1, Integer o2) {.。}指明了具体的处理方法
*/
Comparator<Integer> comparator = new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
if(o1 > o2)
return 1;
else
return -1;
}
};
/**
* public static <T> void sort(T[] a, Comparator<? super T> c) {
* if (c == null) {
* sort(a);//使用默认策略方法
* } else {
* if (LegacyMergeSort.userRequested)
* legacyMergeSort(a, c);//使用策略对象
* else
* TimSort.sort(a, 0, a.length, c, null, 0, 0);
* }
* }
*/
Arrays.sort(a,comparator);
for(Integer i:a)
System.out.println(i);
}
}