一、策略模式
根据具体的需要使用不同的实现方式。比如写一个数组排序方法,根据自己的爱好选择你想要的排序方式。
二、定义一个排序类的抽象方法
package com.StrategyModel; public abstract class SortStrategy { public abstract <T> T[] sort(T[] arr); }
二、写一系列继承这个抽象类的排序类
1、选择排序
package com.StrategyModel; public class SelectSort extends SortStrategy { @SuppressWarnings("unchecked") @Override public <T> T[] sort(T[] arr) { for(int i = 0; i < arr.length - 1; i++) { int n = i; for(int j = i; j < arr.length; j++) { if(((Comparable<T>)arr[n]).compareTo(arr[j]) > 0) { n = j; } } if(n != i) { T temp = arr[i]; arr[i] = arr[n]; arr[n] = temp; } } return arr; } }
2、冒泡排序
package com.StrategyModel; public class BubbleSort extends SortStrategy { @SuppressWarnings("unchecked") @Override public <T> T[] sort(T[] arr) { for(int i = arr.length; i > 1; i-- ) { boolean state = false; for(int j = 0; j < i - 1; j++) { if(((Comparable<T>)arr[j]).compareTo(arr[j + 1]) > 0) { T temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; state = true; } } if(!state) { break; } } return arr; } }
3、插入排序
package com.StrategyModel; public class InsertSort extends SortStrategy { @SuppressWarnings("unchecked") @Override public <T> T[] sort(T[] arr) { for(int i = 1; i < arr.length; i++) { T index = arr[i]; int j = i; while(j > 0 && ((Comparable<T>)arr[j - 1]).compareTo(index) > 0) { arr[j] = arr[j - 1]; j--; } arr[j] = index; } return arr; } }
4、快速排序
package com.StrategyModel; public class QuickSort extends SortStrategy { @Override public <T> T[] sort(T[] arr) { this.quick(arr, 0, arr.length - 1); return arr; } @SuppressWarnings("unchecked") public <T> void quick(T[] arr, int low, int high) { int i, j; T index; if(low >= high) { return ; } i = low; j = high; index = arr[low]; while(i < j) { while(i < j && ((Comparable<T>)arr[j]).compareTo(index) >= 0) { j --; } if(i < j) { arr[i++] = arr[j]; } while(i < j && ((Comparable<T>)arr[i]).compareTo(index) <= 0) { i ++; } if(i < j) { arr[j--] = arr[i]; } } arr[i] = index; this.quick(arr, low, i - 1); this.quick(arr, i + 1, high); } }
三、定义一个排序类的调用类Sorter.java
package com.StrategyModel; public class Sorter { private SortStrategy sorterStrategy; public Sorter(SortStrategy sorterStrategy) { this.sorterStrategy = sorterStrategy; } public <T> T[] sort(T[] arr) { if(arr == null) { return null; } return sorterStrategy.sort(arr); } public <T> void print(T[] arr) { if(arr == null) { System.out.println("null"); return; } for (T t : arr) { System.out.println(t); } } }
四、test.java
package com.StrategyModel; public class Test { public static void main(String[] args) { Integer[] arr = {23,45,1346,7,2,77,2367,5,75,23}; //java.swing中的布局管理器使用的就是策略模式 //Sorter sorter = new Sorter(new SelectSort()); //Sorter sorter = new Sorter(new BubbleSort()); //Sorter sorter = new Sorter(new InsertSort()); Sorter sorter = new Sorter(new QuickSort()); arr = sorter.sort(arr); sorter.print(arr); } }