策略模式介绍和代码示例

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

相关推荐
咖啡八杯21 小时前
GoF设计模式——享元模式
java·spring·设计模式·享元模式
:mnong1 天前
学习创建结构行为设计模式
设计模式
w_t_y_y1 天前
Agent设计模式(四)多模态融合模式(Multi-Modal Fusion)
设计模式
zhouhui0011 天前
订单状态的 if-else 地狱上线就崩——状态模式的工业级落地
设计模式
geovindu1 天前
go: Reactor Pattern
开发语言·后端·设计模式·golang·反应器模式
一只旭宝2 天前
【C++入门精讲22】常见设计模式
c++·设计模式
许彰午2 天前
38_Java设计模式之装饰器模式
java·设计模式·装饰器模式
geovindu2 天前
python: Reactor Pattern
开发语言·python·设计模式·反应器模式
workflower2 天前
基于机器学习的设备故障预测分析方法
人工智能·算法·机器学习·设计模式·语言模型·自然语言处理·重构
迷茫运维路2 天前
Golang架构目录设计与设计模式教程
设计模式·golang