策略模式(Strategy Pattern)是一种行为设计模式,它定义了算法家族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化独立于使用算法的客户。

策略模式示例

以下是一个简单的策略模式示例,用于演示如何根据不同的情境选择不同的策略:

  • 快速排序:适用于大量数据,执行速度快。
  • 插入排序:适用于小数据量,简单快速。
// 策略接口
interface SortStrategy {
    void sort(int[] arr);
}

// 快速排序策略实现
class QuickSortStrategy implements SortStrategy {
    public void sort(int[] arr) {
        Arrays.sort(arr);
    }
}

// 插入排序策略实现
class InsertionSortStrategy implements SortStrategy {
    public void sort(int[] arr) {
        for (int i = 1; i < arr.length; i++) {
            int key = arr[i];
            int j = i - 1;

            while (j >= 0 && arr[j] > key) {
                arr[j + 1] = arr[j];
                j--;
            }
            arr[j + 1] = key;
        }
    }
}

// 策略上下文
class Context {
    private SortStrategy strategy;

    public void setStrategy(SortStrategy strategy) {
        this.strategy = strategy;
    }

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

// 使用示例
public class StrategyPatternExample {
    public static void main(String[] args) {
        Context context = new Context();
        SortStrategy quickSort = new QuickSortStrategy();
        context.setStrategy(quickSort);
        context.sort(new int[]{3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5});

        SortStrategy insertionSort = new InsertionSortStrategy();
        context.setStrategy(insertionSort);
        context.sort(new int[]{3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5});
    }
}

扩展阅读

想要了解更多设计模式,可以阅读本站的其他相关文章,例如设计模式概览

返回首页