• 设计模式——策略模式


    一、策略模式

    1.1 概述

    在现实生活中常常遇到实现某种目标存在多种策略可供选择的情况,例如,出行旅游可以乘坐飞机、乘坐火车、骑自行车或自己开私家车等,超市促销可以釆用打折、送商品、送积分等方法。

    在软件开发中也常常遇到类似的情况,当实现某一个功能存在多种算法或者策略,我们可以根据环境或者条件的不同选择不同的算法或者策略来完成该功能,如数据排序策略有冒泡排序、选择排序、插入排序、二叉树排序等。

    如果使用多重条件转移语句实现(即硬编码),不但使条件语句变得很复杂,而且增加、删除或更换算法要修改原代码,不易维护,违背开闭原则。如果采用策略模式就能很好解决该问题。

    1.2 定义

    该模式定义了一系列算法,并将每个算法封装起来,使它们可以相互替换,且算法的变化不会影响使用算法的客户。策略模式属于对象行为模式,它通过对算法进行封装,把使用算法的责任和算法的实现分割开来,并委派给不同的对象对这些算法进行管理。

    1.3 结构

    • 抽象策略(Strategy)类:定义了一个公共接口,各种不同的算法以不同的方式实现这个接口,环境角色使用这个接口调用不同的算法,一般使用接口或抽象类实现。
    • 具体策略(Concrete Strategy)类:实现了抽象策略定义的接口,提供具体的算法实现。
    • 环境(Context)类:持有一个策略类的引用,最终给客户端调用。

    在这里插入图片描述

    1.4 案例

    public class StrategyPattern {
        public static void main(String[] args) {
            Context c = new Context();
            Strategy s = new ConcreteStrategyA();
            c.setStrategy(s);
            c.strategyMethod();
            System.out.println("-----------------");
            s = new ConcreteStrategyB();
            c.setStrategy(s);
            c.strategyMethod();
        }
    }
    //抽象策略类
    interface Strategy {
        public void strategyMethod();    //策略方法
    }
    //具体策略类A
    class ConcreteStrategyA implements Strategy {
        public void strategyMethod() {
            System.out.println("具体策略A的策略方法被访问!");
        }
    }
    //具体策略类B
    class ConcreteStrategyB implements Strategy {
        public void strategyMethod() {
            System.out.println("具体策略B的策略方法被访问!");
        }
    }
    //环境类
    class Context {
        private Strategy strategy;
        public Strategy getStrategy() {
            return strategy;
        }
        public void setStrategy(Strategy strategy) {
            this.strategy = strategy;
        }
        public void strategyMethod() {
            strategy.strategyMethod();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41

    1.5 优缺点

    优点

    • 多重条件语句不易维护,而使用策略模式可以避免使用多重条件语句,如 if…else 语句、switch…case 语句。
    • 策略模式提供了一系列的可供重用的算法族,恰当使用继承可以把算法族的公共代码转移到父类里面,从而避免重复的代码。
    • 策略模式提供了对开闭原则的完美支持,可以在不修改原代码的情况下,灵活增加新算法。
    • 策略模式把算法的使用放到环境类中,而算法的实现移到具体策略类中,实现了二者的分离。

    缺点

    • 客户端必须理解所有策略算法的区别,以便适时选择恰当的算法类。
    • 策略模式造成很多的策略类,增加维护难度。

    1.6 使用场景

    • 一个系统需要动态地在几种算法中选择一种时,可将每个算法封装到策略类中。
    • 一个类定义了多种行为,并且这些行为在这个类的操作中以多个条件语句的形式出现,可将每个条件分支移入它们各自的策略类中以代替这些条件语句。
    • 系统中各算法彼此完全独立,且要求对客户隐藏具体算法的实现细节时。
    • 系统要求使用算法的客户不应该知道其操作的数据时,可使用策略模式来隐藏与算法相关的数据结构。
    • 多个类只区别在表现行为不同,可以使用策略模式,在运行时动态选择具体要执行的行为。

    1.7 JDK源码解析

    Comparator 中的策略模式。在Arrays类中有一个 sort() 方法,如下:

    public class Arrays{
        public static <T> void sort(T[] a, Comparator<? super T> c) {
            if (c == null) {
                sort(a);
            } else {
                if (LegacyMergeSort.userRequested)
                    legacyMergeSort(a, c);
                else
                    TimSort.sort(a, 0, a.length, c, null, 0, 0);
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    Arrays就是一个环境角色类,这个sort方法可以传一个新策略让Arrays根据这个策略来进行排序。就比如下面的测试类。

    public class demo {
        public static void main(String[] args) {
    
            Integer[] data = {12, 2, 3, 2, 4, 5, 1};
            // 实现降序排序
            Arrays.sort(data, new Comparator<Integer>() {
                public int compare(Integer o1, Integer o2) {
                    return o2 - o1;
                }
            });
            System.out.println(Arrays.toString(data)); //[12, 5, 4, 3, 2, 2, 1]
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    这里我们在调用Arrays的sort方法时,第二个参数传递的是Comparator接口的子实现类对象。所以Comparator充当的是抽象策略角色,而具体的子实现类充当的是具体策略角色。环境角色类(Arrays)应该持有抽象策略的引用来调用。那么,Arrays类的sort方法到底有没有使用Comparator子实现类中的 compare() 方法吗?让我们继续查看TimSort类的 sort() 方法,代码如下:

    class TimSort<T> {
        static <T> void sort(T[] a, int lo, int hi, Comparator<? super T> c,
                             T[] work, int workBase, int workLen) {
            assert c != null && a != null && lo >= 0 && lo <= hi && hi <= a.length;
    
            int nRemaining  = hi - lo;
            if (nRemaining < 2)
                return;  // Arrays of size 0 and 1 are always sorted
    
            // If array is small, do a "mini-TimSort" with no merges
            if (nRemaining < MIN_MERGE) {
                int initRunLen = countRunAndMakeAscending(a, lo, hi, c);
                binarySort(a, lo, hi, lo + initRunLen, c);
                return;
            }
            ...
        }   
            
        private static <T> int countRunAndMakeAscending(T[] a, int lo, int hi,Comparator<? super T> c) {
            assert lo < hi;
            int runHi = lo + 1;
            if (runHi == hi)
                return 1;
    
            // Find end of run, and reverse range if descending
            if (c.compare(a[runHi++], a[lo]) < 0) { // Descending
                while (runHi < hi && c.compare(a[runHi], a[runHi - 1]) < 0)
                    runHi++;
                reverseRange(a, lo, runHi);
            } else {                              // Ascending
                while (runHi < hi && c.compare(a[runHi], a[runHi - 1]) >= 0)
                    runHi++;
            }
    
            return runHi - lo;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37

    上面的代码中最终会跑到 countRunAndMakeAscending() 这个方法中。我们可以看见,只用了compare方法,所以在调用Arrays.sort方法只传具体compare重写方法的类对象就行,这也是Comparator接口中必须要子类实现的一个方法。

  • 相关阅读:
    3D数字孪生:从3D数据采集到3D内容分析
    Jenkins 带参数执行shell脚本
    LinkedIn DataHub --- 经验分享
    新加坡国际学校年年IB成绩领先,到底有何优势?
    【JavaWeb】会话 cookie
    如果非要在多线程中使用 ArrayList 会发生什么?
    vue插件的使用方法
    LeetCode 1413.逐步求和得到正数的最小值
    Python-Flask快速上手
    OS2.2.5:调度算法之时间片轮转调度、优先级调度、多级反馈队列调度
  • 原文地址:https://blog.csdn.net/qq_51114283/article/details/125905794