策略模式介绍和代码示例

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

相关推荐
深情不及里子3 小时前
每天认识一个设计模式-桥接模式:在抽象与实现的平行宇宙架起彩虹桥
设计模式·桥接模式
Hanson Huang4 小时前
23种设计模式-模板方法(Template Method)设计模式
java·设计模式·模板方法模式·行为型设计模式
木子庆五4 小时前
Android设计模式之观察者模式
android·观察者模式·设计模式
此木|西贝5 小时前
【设计模式】策略模式
设计模式·策略模式
有龍则灵6 小时前
责任链设计模式在Dubbo中的应用深度解析
设计模式·dubbo
渊渟岳7 小时前
掌握设计模式--迭代器模式
设计模式
Hanson Huang19 小时前
23种设计模式-享元(Flyweight)设计模式
java·设计模式·享元模式·结构型设计模式
Aphelios3801 天前
Java全栈面试宝典:内存模型与Spring设计模式深度解析
java·学习·spring·设计模式·云原生·面试
NorthCastle1 天前
设计模式-结构型模式-外观模式
java·设计模式·外观模式
刀法如飞1 天前
MVC与MVP/MVVM/DDD架构对比,不同语言实现
设计模式·架构·mvc