以下是应用Java实现冒泡排序、抉择排序和疾速排序的示例代码,应用策略模式实现:

  1. 首先,定义一个策略接口 SortingStrategy,蕴含一个排序办法 sort:

    public interface SortingStrategy { void sort(int[] array);}
  2. 而后,实现三个具体的策略类,别离代表不同的排序算法:

    public class BubbleSortStrategy implements SortingStrategy { @Override public void sort(int[] array) {     int n = array.length;     for (int i = 0; i < n - 1; i++) {         for (int j = 0; j < n - i - 1; j++) {             if (array[j] > array[j + 1]) {                 int temp = array[j];                 array[j] = array[j + 1];                 array[j + 1] = temp;             }         }     }     System.out.println("Sorting using bubble sort: " + Arrays.toString(array)); }}
    public class SelectionSortStrategy implements SortingStrategy { @Override public void sort(int[] array) {     int n = array.length;     for (int i = 0; i < n - 1; i++) {         int minIndex = i;         for (int j = i + 1; j < n; j++) {             if (array[j] < array[minIndex]) {                 minIndex = j;             }         }         int temp = array[minIndex];         array[minIndex] = array[i];         array[i] = temp;     }     System.out.println("Sorting using selection sort: " + Arrays.toString(array)); }}
    public class QuickSortStrategy implements SortingStrategy { @Override public void sort(int[] array) {     quickSort(array, 0, array.length - 1);     System.out.println("Sorting using quick sort: " + Arrays.toString(array)); } private void quickSort(int[] array, int low, int high) {     if (low < high) {         int pivot = partition(array, low, high);         quickSort(array, low, pivot - 1);         quickSort(array, pivot + 1, high);     } } private int partition(int[] array, int low, int high) {     int pivot = array[high];     int i = low - 1;     for (int j = low; j < high; j++) {         if (array[j] < pivot) {             i++;             int temp = array[i];             array[i] = array[j];             array[j] = temp;         }     }     int temp = array[i + 1];     array[i + 1] = array[high];     array[high] = temp;     return i + 1; }}
  3. 接下来,能够应用策略模式进行排序操作:

    public class Main { public static void main(String[] args) {     int[] array = {5, 2, 8, 3, 1};     // 抉择排序策略并创立相应的策略对象     SortingStrategy sortingStrategy = new BubbleSortStrategy();     // 或者 SortingStrategy sortingStrategy = new SelectionSortStrategy();     // 或者 SortingStrategy sortingStrategy = new QuickSortStrategy();     // 执行排序操作     sortingStrategy.sort(array); }}
在上述示例中,咱们定义了三种排序策略:冒泡排序、抉择排序和疾速排序。依据需要,咱们抉择其中一种策略,并将其传递给策略对象 sortingStrategy。而后,调用 sort 办法执行排序操作。
输入后果将依据所选的排序策略不同而有所不同。
策略模式容许在运行时动静抉择不同的策略,因而能够依据理论需要灵便地切换排序算法,而不须要批改应用排序策略的代码。