策略模式学习demo
1.策略模式测试类
public class StrategyPatternDemo { public static void main(String[] args) { int[] array = {64, 25, 12, 22, 11}; SortContext context = new SortContext(new BubbleSort()); context.sort(array); // 使用冒泡排序 System.out.println("排序后的数组: "); for (int num : array) { System.out.print(num + " "); } System.out.println(); // 重新设置排序策略为选择排序 context.setSortStrategy(new SelectionSort()); context.sort(array); // 使用选择排序 System.out.println("排序后的数组: "); for (int num : array) { System.out.print(num + " "); } } }
2.排序策略接口
public interface SortStrategy { void sort(int[] array); }
3.排序策略类
1.选择排序 public class SelectionSort implements SortStrategy { @Override public void sort(int[] array) { System.out.println("使用选择排序"); 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; } } }
2.冒泡排序
public class BubbleSort implements SortStrategy { @Override public void sort(int[] array) { System.out.println("使用冒泡排序"); 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; } } } } }
4.策略上下文
public class SortContext { private SortStrategy sortStrategy; public SortContext(SortStrategy sortStrategy) { this.sortStrategy = sortStrategy; } public void setSortStrategy(SortStrategy sortStrategy) { this.sortStrategy = sortStrategy; } public void sort(int[] arr) { sortStrategy.sort(arr); } }