设计模式-12-策略模式

来源:互联网 发布:网络打印机 编辑:程序博客网 时间:2024/06/04 19:39

策略模式:一个类的行为或其算法可以在运行时更改。
这里写图片描述

策略模式就是对这段代码的改进

public void selectSort(String type){        if("type1".equals(type)){            //选择快速排序        }        else if("type2".equals(type)){            //选择插入排序        }        else if("type3".equals(type)){            //选择冒泡排序        }        else if("type4".equals(type)){            //选择选择排序        }        ......    }

接口

public interface Sort{    public abstract int[] sort(int arr[]);}

相应的策略

//冒泡排序public class BubbleSort implements Sort{    public int[] sort(int arr[]){       int len=arr.length;       for(int i=0;i<len;i++){           for(int j=i+1;j<len;j++){              int temp;              if(arr[i]>arr[j]){                  temp=arr[j];                  arr[j]=arr[i];                  arr[i]=temp;              }                        }        }        System.out.println("冒泡排序");        return arr;    }}
//插入排序public class InsertionSort implements Sort {    public int[] sort(int arr[]) {        int len = arr.length;        for (int i = 1; i < len; i++) {            int j;            int temp = arr[i];            for (j = i; j > 0; j--) {                if (arr[j - 1] > temp) {                    arr[j] = arr[j - 1];                } else                    break;            }            arr[j] = temp;        }        System.out.println("插入排序");        return arr;    }}
//选择排序public class SelectionSort implements Sort {    public int[] sort(int arr[]) {        int len = arr.length;        int temp;        for (int i = 0; i < len; i++) {            temp = arr[i];            int j;            int samllestLocation = i;            for (j = i + 1; j < len; j++) {                if (arr[j] < temp) {                    temp = arr[j];                    samllestLocation = j;                }            }            arr[samllestLocation] = arr[i];            arr[i] = temp;        }        System.out.println("选择排序");        return arr;    }}

实例化策略的时候选择相应的排序,相当于if中的条件

public class ArrayHandler{    private Sort sortObj;    public int[] sort(int arr[])    {        sortObj.sort(arr);        return arr;    }    public void setSortObj(Sort sortObj) {        this.sortObj = sortObj;     }}

测试

public class Client{    public static void main(String args[])    {       int arr[]={1,4,6,2,5,3,7,10,9};       int result[];       ArrayHandler ah=new ArrayHandler();       Sort sort = new SelectionSort();    //使用选择排序       ah.setSortObj(sort); //设置具体策略       result=ah.sort(arr);       for(int i=0;i<result.length;i++)       {               System.out.print(result[i] + ",");       }    }}