设计模式-策略模式

策略模式

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

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

相关推荐
触底反弹2 小时前
🤯 面试被问 AI Workflow 和 Agent 有啥区别?3 张图 + 2 段代码讲清楚!
人工智能·设计模式·面试
张小姐的猫19 小时前
【Linux】网络编程 —— HTTP协议(上)
linux·运维·服务器·网络·http·单例模式·策略模式
杨充1 天前
10.可测试性实战设计
设计模式·开源·代码规范
杨充1 天前
9.重构十二式的实战
设计模式·开源·代码规范
杨充1 天前
6.设计原则的全景图
设计模式·开源·全栈
杨充1 天前
2.面向对象的特性
设计模式
杨充1 天前
7.SOLID原则案例汇
设计模式·开源·全栈
杨充1 天前
8.反模式与坏味道
设计模式·开源·代码规范
杨充1 天前
3.接口vs抽象类比较
设计模式