设计模式-策略模式

前言:

设计模式不用就忘,之前在博客园写的设计模式就不放到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 是上下文,它使用策略来执行排序操作。客户端代码可以根据需要选择不同的策略对象。

相关推荐
ghost1434 小时前
C#学习第23天:面向对象设计模式
开发语言·学习·设计模式·c#
西北大程序猿4 小时前
日志与策略模式
策略模式
敲代码的 蜡笔小新7 小时前
【行为型之迭代器模式】游戏开发实战——Unity高效集合遍历与场景管理的架构精髓
unity·设计模式·c#·迭代器模式
敲代码的 蜡笔小新1 天前
【行为型之命令模式】游戏开发实战——Unity可撤销系统与高级输入管理的架构秘钥
unity·设计模式·架构·命令模式
m0_555762901 天前
D-Pointer(Pimpl)设计模式(指向实现的指针)
设计模式
小Mie不吃饭1 天前
【23种设计模式】分类结构有哪些?
java·设计模式·设计规范
君鼎2 天前
C++设计模式——单例模式
c++·单例模式·设计模式
敲代码的 蜡笔小新2 天前
【行为型之中介者模式】游戏开发实战——Unity复杂系统协调与通信架构的核心秘诀
unity·设计模式·c#·中介者模式
令狐前生2 天前
设计模式学习整理
学习·设计模式
敲代码的 蜡笔小新2 天前
【行为型之解释器模式】游戏开发实战——Unity动态公式解析与脚本系统的架构奥秘
unity·设计模式·游戏引擎·解释器模式