策略模式介绍和代码示例

策略模式(Strategy Pattern)是一种行为设计模式,它定义了一系列算法,并将每一个算法封装起来,使它们可以互换,算法的变化不会影响到使用算法的客户。策略模式让算法独立于其使用者,并且可以根据需要切换算法。

策略模式的关键要素:

  1. 策略接口(Strategy Interface):定义算法的公共接口。
  2. 具体策略类(Concrete Strategy):实现策略接口的具体算法类。
  3. 上下文(Context):使用策略接口来配置和管理具体策略对象。

示例代码:

假设我们有一个简单的排序算法,我们想要根据不同的排序策略(如冒泡排序、选择排序)来排序一个数组。

首先,我们定义一个排序策略接口:

java 复制代码
public interface SortingStrategy {
    void sort(int[] array);
}

然后,我们创建两个具体的排序策略类,实现上述接口:

java 复制代码
public class BubbleSortStrategy implements SortingStrategy {
    public void sort(int[] array) {
        // 冒泡排序算法实现
    }
}
public class SelectionSortStrategy implements SortingStrategy {
    public void sort(int[] array) {
        // 选择排序算法实现
    }
}

接下来,我们创建一个上下文类,它将使用具体的排序策略:

java 复制代码
public class SortContext {
    private SortingStrategy strategy;
    public SortContext(SortingStrategy strategy) {
        this.strategy = strategy;
    }
    public void setStrategy(SortingStrategy strategy) {
        this.strategy = strategy;
    }
    public void executeSort(int[] array) {
        strategy.sort(array);
    }
}

最后,我们可以在客户端代码中根据需要切换不同的排序策略:

java 复制代码
public class StrategyPatternDemo {
    public static void main(String[] args) {
        int[] numbers = { 5, 1, 4, 2, 8 };
        SortContext context = new SortContext(new BubbleSortStrategy());
        context.executeSort(numbers);
        System.out.println("Sorted array with Bubble Sort: " + Arrays.toString(numbers));
        // 切换到选择排序策略
        context.setStrategy(new SelectionSortStrategy());
        context.executeSort(numbers);
        System.out.println("Sorted array with Selection Sort: " + Arrays.toString(numbers));
    }
}

在这个示例中,SortContext是上下文,它依赖于SortingStrategy接口。BubbleSortStrategySelectionSortStrategy是具体的策略实现。客户端代码通过SortContext来使用不同的排序策略,而不需要知道具体的排序细节。这样,算法的变化不会影响客户端代码,符合开闭原则(对扩展开放,对修改封闭)。

相关推荐
萧青山8 分钟前
2026国标合规:Agent Loop合规设计模式的6种循环架构(GB/Z 185.6+Python)
python·设计模式·agent loop·gb/z 185·国标合规
杨充15 小时前
11.DDD与战术建模
设计模式·开源·代码规范
杨充15 小时前
12.综合实战图片框架
设计模式·开源·代码规范
芝士熊爱编程20 小时前
创建型模式-单例模式
java·单例模式·设计模式
咖啡八杯1 天前
GoF设计模式——访问者模式
设计模式·访问者模式
谢栋_1 天前
设计模式从入门到精通之(七)责任链模式
java·设计模式·责任链模式
葬送的代码人生2 天前
别再让 AI 瞎写代码了!Vibe Coding 三步法教你写出靠谱代码
前端·设计模式·架构
无风听海2 天前
Claude Agent Skills 的四种设计模式;从渐进式披露到最小权限
java·算法·设计模式
富贵冼中求2 天前
从单向流到双向 RPC:Agent 通信协议的范式分叉与 ACP 协议实战拆解
设计模式·架构
电子科技圈2 天前
先进封装、芯粒架构和3D集成——先进异构集成亟需兼具标准化与定制化能力的互联及总线IP解决方案
tcp/ip·设计模式·架构·软件构建·代码规范·设计规范