设计模式-策略模式

策略模式

一个类或者算法可以在运行时更改,实现这种功能的方式/方法就称为策略模式。

1.使用步骤

  • 定义策略接口
  • 定义使用策略的客户端类
  • 定义具体的策略类

2.举例

定义策略接口:

java 复制代码
public interface Comparator {
    public int compare(Cat o1, Cat o2);
}

定义使用策略的客户端类:

java 复制代码
public class Sort {
    public static  <T> void  quickSort(Cat[] arr , int l, int r, Comparator comparator){
        if(l>=r) {return;}
        int i = l-1, j = r+1;
        Cat t = arr[(r+l) >> 1];

        while (i<j){
            do {++i;}while (comparator.compare(arr[i], t) < 0);
            do{--j;}while (comparator.compare(arr[j], t) > 0);
            if(i<j) {swap(arr, i, j); }
        }

        quickSort(arr, l, j,comparator);
        quickSort(arr, j+1,r,comparator);
    }

    private static  void swap(Cat[] t, int i, int j){
        Cat temp = t[i];
        t[i] = t[j];
        t[j] = temp;
    }
}

定义具体的策略类:

java 复制代码
public class ComparatorStrategy1 implements Comparator{
    @Override
    public int compare(Cat o1, Cat o2) {
         if(o1.getWeight()>o2.getWeight()){
             return 1;
         }else if(o1.getWeight()<o2.getWeight()){
             return -1;
         }
         return 0;
    }
}

优点:

  • 算法可以自由切换。
  • 避免使用多重条件判断。
  • 扩展性良好。
    缺点:
  • 策略类会增多(通常使用匿名内部类)
  • 所有策略类都需要对外暴露。

总结:在Java排序Arrays.sort就使用到了该种策略模式。此种方式可以使用泛型的方式来进行优化代码。来试试吧!!!

相关推荐
willow2 天前
Axios由浅入深
设计模式·axios
七月丶4 天前
别再手动凑 PR 了:这个 AI Skill 会按仓库习惯自动建分支、拆提交、提 PR
人工智能·设计模式·程序员
刀法如飞4 天前
从程序员到架构师:6大编程范式全解析与实践对比
设计模式·系统架构·编程范式
九狼4 天前
Flutter + Riverpod +MVI 架构下的现代状态管理
设计模式
静水流深_沧海一粟5 天前
04 | 别再写几十个参数的构造函数了——建造者模式
设计模式
StarkCoder5 天前
从UIKit到SwiftUI的迁移感悟:数据驱动的革命
设计模式
阿星AI工作室5 天前
给openclaw龙虾造了间像素办公室!实时看它写代码、摸鱼、修bug、写日报,太可爱了吧!
前端·人工智能·设计模式
_哆啦A梦6 天前
Vibe Coding 全栈专业名词清单|设计模式·基础篇(创建型+结构型核心名词)
前端·设计模式·vibecoding
阿闽ooo9 天前
中介者模式打造多人聊天室系统
c++·设计模式·中介者模式