设计模式-策略模式

策略模式

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

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就使用到了该种策略模式。此种方式可以使用泛型的方式来进行优化代码。来试试吧!!!

相关推荐
vker3 小时前
第 1 天:单例模式(Singleton Pattern)—— 创建型模式
java·设计模式
晨米酱21 小时前
JavaScript 中"对象即函数"设计模式
前端·设计模式
数据智能老司机1 天前
精通 Python 设计模式——分布式系统模式
python·设计模式·架构
数据智能老司机1 天前
精通 Python 设计模式——并发与异步模式
python·设计模式·编程语言
数据智能老司机1 天前
精通 Python 设计模式——测试模式
python·设计模式·架构
数据智能老司机1 天前
精通 Python 设计模式——性能模式
python·设计模式·架构
使一颗心免于哀伤1 天前
《设计模式之禅》笔记摘录 - 21.状态模式
笔记·设计模式
数据智能老司机2 天前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
数据智能老司机2 天前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
烛阴2 天前
【TS 设计模式完全指南】懒加载、缓存与权限控制:代理模式在 TypeScript 中的三大妙用
javascript·设计模式·typescript