返回

以不变应万变,策略模式之妙用

见解分享

策略模式:以不变应万变的应对之道

策略模式,又称政策模式,是一种设计模式,其核心思想是将算法封装为一个个独立的策略类,并通过将算法的选择权外移到客户端,使客户可以根据需求灵活地选择和替换不同的算法。这种设计方式具有很强的灵活性,可以方便地应对需求变化,而无需修改源代码。

策略模式的适用场景

策略模式适用于以下场景:

  • 针对同一问题,有多种不同的处理方式,而这些处理方式内部有所不同。
  • 算法或策略需要经常改变,而不想修改源代码。
  • 需要对算法或策略进行独立测试和维护。

策略模式的优势

  • 提高代码的可重用性。策略模式将算法封装为一个个独立的类,使得这些算法可以被复用。
  • 提高代码的可维护性。策略模式将算法与客户选择权分离,使得算法的维护和修改更加容易。
  • 提高代码的可扩展性。策略模式使得在系统中添加新的算法变得更加容易。

策略模式的局限

  • 策略模式可能会导致系统变得更加复杂。
  • 策略模式可能会导致性能开销。

策略模式的实例

以下是一个使用策略模式的实例:

// 策略接口
interface SortStrategy {
    int[] sort(int[] nums);
}

// 具体策略类:冒泡排序
class BubbleSortStrategy implements SortStrategy {
    @Override
    public int[] sort(int[] nums) {
        for (int i = 0; i < nums.length - 1; i++) {
            for (int j = 0; j < nums.length - i - 1; j++) {
                if (nums[j] > nums[j + 1]) {
                    int temp = nums[j];
                    nums[j] = nums[j + 1];
                    nums[j + 1] = temp;
                }
            }
        }
        return nums;
    }
}

// 具体策略类:选择排序
class SelectionSortStrategy implements SortStrategy {
    @Override
    public int[] sort(int[] nums) {
        for (int i = 0; i < nums.length - 1; i++) {
            int minIndex = i;
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[j] < nums[minIndex]) {
                    minIndex = j;
                }
            }
            int temp = nums[i];
            nums[i] = nums[minIndex];
            nums[minIndex] = temp;
        }
        return nums;
    }
}

// 具体策略类:快速排序
class QuickSortStrategy implements SortStrategy {
    @Override
    public int[] sort(int[] nums) {
        quickSort(nums, 0, nums.length - 1);
        return nums;
    }

    private void quickSort(int[] nums, int low, int high) {
        if (low < high) {
            int partitionIndex = partition(nums, low, high);

            quickSort(nums, low, partitionIndex - 1);
            quickSort(nums, partitionIndex + 1, high);
        }
    }

    private int partition(int[] nums, int low, int high) {
        int pivot = nums[high];
        int i = low - 1;

        for (int j = low; j < high; j++) {
            if (nums[j] < pivot) {
                i++;

                int temp = nums[i];
                nums[i] = nums[j];
                nums[j] = temp;
            }
        }

        int temp = nums[i + 1];
        nums[i + 1] = nums[high];
        nums[high] = temp;

        return i + 1;
    }
}

// 客户类
class SortClient {
    private SortStrategy sortStrategy;

    public SortClient(SortStrategy sortStrategy) {
        this.sortStrategy = sortStrategy;
    }

    public int[] sort(int[] nums) {
        return sortStrategy.sort(nums);
    }
}

// 测试
public class Main {
    public static void main(String[] args) {
        int[] nums = {5, 3, 1, 2, 4};

        SortClient bubbleSortClient = new SortClient(new BubbleSortStrategy());
        int[] sortedNums1 = bubbleSortClient.sort(nums);
        System.out.println("Bubble Sort Result: ");
        for (int num : sortedNums1) {
            System.out.print(num + " ");
        }
        System.out.println();

        SortClient selectionSortClient = new SortClient(new SelectionSortStrategy());
        int[] sortedNums2 = selectionSortClient.sort(nums);
        System.out.println("Selection Sort Result: ");
        for (int num : sortedNums2) {
            System.out.print(num + " ");
        }
        System.out.println();

        SortClient quickSortClient = new SortClient(new QuickSortStrategy());
        int[] sortedNums3 = quickSortClient.sort(nums);
        System.out.println("Quick Sort Result: ");
        for (int num : sortedNums3) {
            System.out.print(num + " ");
        }
        System.out.println();
    }
}

在这个实例中,SortStrategy接口定义了排序算法的通用接口,而BubbleSortStrategySelectionSortStrategyQuickSortStrategy类则实现了具体的排序算法。SortClient类是策略模式的客户类,它通过将不同的策略类传入构造函数来选择不同的排序算法。

通过使用策略模式,我们可以很容易地切换不同的排序算法,而无需修改源代码。这种设计方式提高了代码的可重用性、可维护性和可扩展性。