策略模式介绍和代码示例

策略模式(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来使用不同的排序策略,而不需要知道具体的排序细节。这样,算法的变化不会影响客户端代码,符合开闭原则(对扩展开放,对修改封闭)。

相关推荐
端庄的战斗机6 小时前
javascript 设计模式(文章很长,请自备瓜子,水果和眼药水)
开发语言·javascript·设计模式
饼干哥哥12 小时前
我开发了一个「吃掉」别人Skill来升级的饕餮.Skill,现在免费开源
人工智能·设计模式·开源
CaffeinePro13 小时前
什么是系统架构?架构师到底在做什么?
设计模式·架构
AI人工智能+电脑小能手15 小时前
【大白话说Java面试题 第156题】【06_Spring篇】第16题:Spring 用到了哪些设计模式?
java·spring·设计模式·代理模式·工厂模式
前端百草阁17 小时前
JavaScript 设计模式(23 种)
开发语言·前端·javascript·设计模式
geovindu17 小时前
java: Singleton Pattern
java·开发语言·后端·单例模式·设计模式·创建型模式
geovindu1 天前
python: Functional Options Pattern
开发语言·后端·python·设计模式·惯用法模式·函数式选项模式
Kel1 天前
Pregel 为什么会成为LangGraph编排的心脏
人工智能·设计模式·架构
会周易的程序员2 天前
microLog 后端开发指南
开发语言·c++·物联网·设计模式·日志·iot·aiot
geovindu2 天前
go: Functional Options Pattern
开发语言·后端·设计模式·golang·函数式选项模式’·惯用法模式