策略模式(重要):
对象行为型模式,将一系列算法独立地封装起来,并且可以相互替换。将算法的定义和使用分开,将算法的定义放在专门的策略类中,一个策略类封装一种算法
策略模式的结构:环境类(使用算法的类),抽象策略类,具体策略类
区别策略模式和状态模式:
(1)对象存在多种状态,状态之间可以相互转换,不同的状态有不同的行为,使用状态模式。而对象只有一种状态时,完成一项功能有多种算法,算法之间可以相互替换,使用策略模式
(2)策略模式中,环境类和策略类是单向关联,而状态模式环境类和策略类是双向关联
(3)策略模式中,用户需要知道应该使用哪一个策略类,而状态模式中用户不需关心具体的状态
策略模式的适用场景:
1.算法的自由替换和扩展
2.完成一项功能有多种解决方案(算法),系统动态地从几种算法中选择一个
3.避免使用多重条件选择语句
策略模式的优点:
1.增加新的算法不需修改原有代码,符合开闭原则,易于扩展,较为灵活
2.避免使用多重条件选择语句
策略模式的缺点:
1.用户要知道具体策略类之间的区别,知道什么时候该选择哪一种策略,这增加了使用的难度
2.系统中可能会产生很多策略类和对象,增加了系统的复杂度,可使用享元模式减少对象的数量
策略模式的例子:
抽象策略类
public abstract class MySort {
public abstract void sort(double[] arr);
}
策略类
public class QuickSort extends MySort{
/**
* @Description: TODO
* @author doudou
* @date 2019年10月19日
* @throws
* @return
* @see structual.StrategyPattern.MySort#sort()
*/
@Override
public void sort(double[] arr) {
int low = 0,high = arr.length -1;
this.quickSort(arr, low, high);
}
public void quickSort(double[] arr,int low,int high) {
if (low < high) {
int pivotloc = partition(arr,low,high);
quickSort(arr, low, pivotloc-1);
quickSort(arr, pivotloc+1, high);
}
}
private int partition(double[] arr,int low,int high) {
double temp = arr[low];
while (low < high) {
while(low < high && arr[high] > temp) {
--high;
}
arr[low] = arr[high];
while(low < high && arr[low] < temp) {
++low;
}
arr[high] = arr[high];
}
arr[low] = temp;
return low;
}
}
public class InsertSort extends MySort{
/**
* @Description: 直接插入排序
* @author doudou
* @date 2019年10月19日
* @param arr
* @throws
* @return
* @see structual.StrategyPattern.MySort#sort(double[])
*/
@Override
public void sort(double[] arr) {
for (int i = 1; i < arr.length; ++i) {
if (arr[i] < arr[i-1]) {
double temp = arr[i];//记下待插入的记录
int j = i-1;
for (; j>=0 && temp < arr[j]; --j) {//寻找插入的位置
arr[j+1] = arr[j];//将记录后移
}
arr[j+1] = temp;//插入
}
}
}
}
public class BubbleSort extends MySort{
public static void main(String[] args) {
double[] arr = {5,3,2,1,0};
new BubbleSort().sort(arr);
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]+" ");
}
}
/**
* @Description: 冒泡排序
* @author doudou
* @date 2019年10月19日
* @param arr
* @throws
* @return
* @see structual.StrategyPattern.MySort#sort(double[])
*/
@Override
public void sort(double[] arr) {
for (int i = 1; i < arr.length; i++) {
for (int j = 0; j < arr.length-i; j++) {
if (arr[j] > arr[j+1]) {
double temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
}
环境类
public class ArrayHandler {
private MySort mySort;
public void setMySort(MySort mySort) {
this.mySort = mySort;
}
public void sort(double[] arr) {
this.mySort.sort(arr);
}
}
测试类
public class Main {
public static void main(String[] args) {
ArrayHandler arrayHandler = new ArrayHandler();
MySort mySort = new QuickSort();
arrayHandler.setMySort(mySort);
double[] arr = {5,4,3,2,1};
arrayHandler.sort(arr);
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]+" ");
}
}
}
策略模式的应用:
1.Java SE的容器布局管理器