设计模式-策略模式

前言:

设计模式不用就忘,之前在博客园写的设计模式就不放到csdn中了,加个锚点,方便日后温习:

设计模式------创建型模式之工厂模式 - 山月云星 - 博客园 (cnblogs.com)

正文:

策略模式允许在运行时选择算法或策略,而无需硬编码。下面是一个简单的策略模式示例,涉及两种不同的排序策略:升序和降序

java 复制代码
// 策略接口 
public interface SortingStrategy { 
    void sort(int[] numbers); 
}

创建两个实现了该策略接口的具体策略类

java 复制代码
// 升序排序策略
public class AscendingSortStrategy implements SortingStrategy {
    @Override
    public void sort(int[] numbers) {
        Arrays.sort(numbers);
    }
}

// 降序排序策略
public class DescendingSortStrategy implements SortingStrategy {
    @Override
    public void sort(int[] numbers) {
        int n = numbers.length;
        for (int i = 0; i < n-1; i++) {
            for (int j = 0; j < n-i-1; j++) {
                if (numbers[j] > numbers[j+1]) {
                    // 交换元素
                    int temp = numbers[j];
                    numbers[j] = numbers[j+1];
                    numbers[j+1] = temp;
                }
            }
        }
    }
}

创建一个上下文类,它将使用选定的策略来执行操作

java 复制代码
public class Sorter { 
  private SortingStrategy strategy;
  
  public Sorter(SortingStrategy strategy) {
    this.strategy = strategy;
  }

  public void sortNumbers(int[] numbers) {
    strategy.sort(numbers);
  }
}

最后,客户端代码可以动态选择并使用不同的排序策略

java 复制代码
public class ClientCode {
    public static void main(String[] args) {
        int[] numbers = {5, 3, 8, 1, 9};

        Sorter ascendingSorter = new Sorter(new AscendingSortStrategy());
        ascendingSorter.sortNumbers(numbers);
        System.out.println("Ascending order: " + Arrays.toString(numbers));

        Sorter descendingSorter = new Sorter(new DescendingSortStrategy());
        descendingSorter.sortNumbers(numbers);
        System.out.println("Descending order: " + Arrays.toString(numbers));
    }
}

SortingStrategy 是策略接口,AscendingSortStrategy 和 DescendingSortStrategy 是具体的策略实现,Sorter 是上下文,它使用策略来执行排序操作。客户端代码可以根据需要选择不同的策略对象。

相关推荐
静水流深_沧海一粟13 小时前
04 | 别再写几十个参数的构造函数了——建造者模式
设计模式
StarkCoder13 小时前
从UIKit到SwiftUI的迁移感悟:数据驱动的革命
设计模式
阿星AI工作室21 小时前
给openclaw龙虾造了间像素办公室!实时看它写代码、摸鱼、修bug、写日报,太可爱了吧!
前端·人工智能·设计模式
_哆啦A梦2 天前
Vibe Coding 全栈专业名词清单|设计模式·基础篇(创建型+结构型核心名词)
前端·设计模式·vibecoding
阿闽ooo5 天前
中介者模式打造多人聊天室系统
c++·设计模式·中介者模式
小米4965 天前
js设计模式 --- 工厂模式
设计模式
头发还在的女程序员5 天前
【免费下载】企业能源管理系统
小程序·策略模式·能源管理
前端 贾公子5 天前
React 和 Vue 都离不开的表单验证库 async-validator 之策略模式的应用 (上)
vue.js·react.js·策略模式
逆境不可逃5 天前
【从零入门23种设计模式08】结构型之组合模式(含电商业务场景)
线性代数·算法·设计模式·职场和发展·矩阵·组合模式
驴儿响叮当20105 天前
设计模式之状态模式
设计模式·状态模式