策略模式定义了一个算法族,分别封装起来,使得它们之间可以互相变换。策略让算法的变化独立于使用它的客户。


Let's create a simple example in Java to demonstrate the Strategy pattern with sorting algorithms. In this example, we'll define a SortingStrategy interface representing the strategy for sorting an array. We'll then create concrete strategies for different sorting algorithms, such as Bubble Sort and Quick Sort. Finally, we'll have a context class that utilizes these strategies.

Here's how you can implement it:

Step 1: Define the Sorting Strategy Interface

public interface SortingStrategy {
    void sort(int[] array);
}

Step 2: Implement Concrete Strategies

Bubble Sort Strategy

public class BubbleSortStrategy implements SortingStrategy {
    public void sort(int[] array) {
        boolean swapped;
        for (int i = 0; i < array.length - 1; i++) {
            swapped = false;
            for (int j = 0; j < array.length - i - 1; j++) {
                if (array[j] > array[j + 1]) {
                    // swap array[j] and array[j+1]
                    int temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;
                    swapped = true;
                }
            }
            if (!swapped) break;
        }
    }
}

Quick Sort Strategy

public class QuickSortStrategy implements SortingStrategy {
    public void sort(int[] array) {
        quickSort(array, 0, array.length - 1);
    }

    private void quickSort(int[] array, int begin, int end) {
        if (begin < end) {
            int partitionIndex = partition(array, begin, end);

            quickSort(array, begin, partitionIndex-1);
            quickSort(array, partitionIndex+1, end);
        }
    }

    private int partition(int[] array, int begin, int end) {
        int pivot = array[end];
        int i = (begin - 1);

        for (int j = begin; j < end; j++) {
            if (array[j] <= pivot) {
                i++;

                int swapTemp = array[i];
                array[i] = array[j];
                array[j] = swapTemp;
            }
        }

        int swapTemp = array[i + 1];
        array[i + 1] = array[end];
        array[end] = swapTemp;

        return i + 1;
    }
}

Step 3: Context Class

public class SortingContext {
    private SortingStrategy strategy;

    public void setSortingMethod(SortingStrategy strategy) {
        this.strategy = strategy;
    }

    public void sortArray(int[] array) {
        strategy.sort(array);
    }
}

Step 4: Using the Strategy Pattern

public class StrategyPatternDemo {
    public static void main(String[] args) {
        SortingContext context = new SortingContext();

        int[] numbers = {34, 2, 19, 45, 6, 18};

        // Using Bubble Sort
        context.setSortingMethod(new BubbleSortStrategy());
        context.sortArray(numbers);
        System.out.println("Sorted using bubble sort: " + Arrays.toString(numbers));

        // Switch to Quick Sort
        context.setSortingMethod(new QuickSortStrategy());
        context.sortArray(numbers);
        System.out.println("Sorted using quick sort: " + Arrays.toString(numbers));
    }
}

In this example, the SortingContext class uses different sorting strategies. You can easily extend this by adding more strategies for different sorting algorithms without modifying the existing classes, adhering to the open/closed principle. This design allows for flexibility and the ability to change sorting behavior at runtime.

标签: none

评论已关闭