设计模式(二)策略模式

设计模式(二)策略模式

策略模式(strategy)

原理

封装的是一个接口(策略)的实现

常见应用

Compartor接口就是我们常用的策略

代码示例

  • client代码

    public class Sorter<T> {
    
        public void sort(T[] arr, Comparator<T> comparator) {
            for(int i=0; i<arr.length - 1; i++) {
                int minPos = i;
    
                for(int j=i+1; j<arr.length; j++) {
                    minPos = comparator.compare(arr[j],arr[minPos])==-1 ? j : minPos;
                }
                swap(arr, i, minPos);
            }
        }
    
        //sort(int)
    
        void swap(T[] arr, int i, int j) {
            T temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        }
    }
    
  • Compartor接口(自定义)

    @FunctionalInterface
    public interface Comparator<T> {
        int compare(T o1, T o2);
    
        default void m() {
            System.out.println("m");
        }
    }
    
  • Compartor实现

    public class CatHeightComparator implements Comparator<Cat> {
        @Override
        public int compare(Cat o1, Cat o2) {
            if(o1.height > o2.height) return -1;
            else if (o1.height < o2.height) return 1;
            else return 0;
        }
    }
    
  • 测试方法

    public class Main {
        public static void main(String[] args) {
            //int[] a = {9, 2, 3, 5, 7, 1, 4};
            Cat[] a = {new Cat(3, 3), new Cat(5, 5), new Cat(1, 1)};
            //Dog[] a = {new Dog(3), new Dog(5), new Dog(1)};
            Sorter<Cat> sorter = new Sorter<>();
            sorter.sort(a, (o1, o2)->{
                if(o1.weight < o2.weight) return -1;
                else if (o1.weight>o2.weight) return 1;
                else return 0;
            });
            System.out.println(Arrays.toString(a));
        }
    }
    

在这里插入图片描述

  • 关键点在于

    需要定义一个新的排序只需要新建一个排序策略并传入比较算法中即可

    对修改关闭,对扩展开放

知识点

  • 策略模式可以理解为switch的一种封装

  • 函数式接口:只有一个实现方法的接口 @FunctionalInterface

总结

可以考虑使用配置文件记录类的全路径名,通过反射初始化类的实例,保证程序逻辑变更时不需要修改判断的逻辑。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值