策略模式介绍和代码示例

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

相关推荐
ShareBeHappy_Qin15 小时前
Spring 中使用的设计模式
java·spring·设计模式
Asort1 天前
JavaScript设计模式(十四)——命令模式:解耦请求发送者与接收者
前端·javascript·设计模式
秉承初心1 天前
Java 23种设计模式的详细解析
java·设计模式
TsengOnce1 天前
设计模式(解释器模式(Interpreter Pattern)结构|原理|优缺点|场景|示例
设计模式·解释器模式
猫头虎1 天前
OpenAI发布构建AI智能体的实践指南:实用框架、设计模式与最佳实践解析
人工智能·设计模式·开源·aigc·交互·pip·ai-native
昨天的猫1 天前
项目中原来策略模式这么玩才有意思😁😁😁
设计模式
Mr_WangAndy1 天前
C++设计模式_行为型模式_迭代器模式Iterator
c++·设计模式·迭代器模式
白衣鸽子1 天前
【基础数据篇】数据遍历大师:Iterator模式
后端·设计模式
muxin-始终如一1 天前
系统重构过程以及具体方法
设计模式·重构
Mr_WangAndy2 天前
C++设计模式_行为型模式_责任链模式Chain of Responsibility
c++·设计模式·责任链模式·行为型模式