• 详解设计模式:策略模式


    策略模式(Strategy Pattern)也被称为政策模式(Policy Pattern),是在 GoF 23 种设计模式中定义了的行为型模式。

    策略模式 是针对一组算法,将每一个算法封装到具有共同接口的独立的类中,使得它们可以互换,被封装起来的算法具有独立性外部不可改变其特性。

    本片文章内容包括:关于策略模式、策略模式 Demo(伪代码)、策略模式的应用(Comparator 中的策略模式)



    一、关于策略模式

    1、关于策略模式

    策略模式(Strategy Pattern)也被称为政策模式(Policy Pattern),是在 GoF 23 种设计模式中定义了的行为型模式。

    策略模式 是针对一组算法,将每一个算法封装到具有共同接口的独立的类中,使得它们可以互换,被封装起来的算法具有独立性外部不可改变其特性。

    策略模式 在实际的项目开发中,这个模式也比较常用。最常见的应用场景是,利用它来避免冗长的 if-else 或 switch 分支判断。不过,它的作用还不止如此。它也可以像模板模式那样,提供框架的扩展点等等。

    2、关于策略模式的构成

    策略模式主要由 3 种角色构成:

    • 环境类(StrategyContext):策略上下文对象,维护指向具体策略的引用,通过策略接口 Strategy 与对象进行沟通。
    • 抽象策略类(Strategy):策略接口,定义统一的策略入口方法,留给具体策略类实现,且供 StrategyContext 调用。
    • 具体策略类(ConcreteStrategy):具体的策略类,实现 Strategy,提供各种不同的算法。
    3、关于策略模式的XML

    在这里插入图片描述

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

    # 策略模式优点

    • 策略模式符合开闭原则;
    • 避免了使用多重条件语句。如 if…else…语句、switch语句;
    • 使用策略模式可以提高算法的保密性和安全性。

    # 策略模式缺点

    • 客户端必须知道所有策略,并自行决定使用那种策略;
    • 代码中会产生非常多的策略,增加维护难度;
    • 如果业务逻辑不是很复杂,强行使用策略模式会增加程序的复杂度。

    二、策略模式 Demo(伪代码)

    1、伪代码 Demo 实现

    # Context 环境类

    public class Context {
    
        /**
         * 持有一个具体策略的对象
         */
        private final Strategy strategy;
    
        /**
         * 构造函数,传入一个具体策略对象
         *
         * @param strategy 具体策略对象
         */
        public Context(Strategy strategy) {
            this.strategy = strategy;
        }
    
        /**
         * 策略方法
         */
        public void contextInterface() {
    
            strategy.interfaceStrategy();
        }
    
    }
    
    • 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

    # Strategy 抽象策略类

    public interface Strategy {
        /**
         * 策略方法
         */
        public void interfaceStrategy();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    # ConcreteStrategy 具体策略类

    public class ConcreteStrategyA implements Strategy {
    
        @Override
        public void interfaceStrategy() {
            //相关的业务
        }
    
    }
    public class ConcreteStrategyB implements Strategy {
    
        @Override
        public void interfaceStrategy() {
            //相关的业务
        }
    
    }
    public class ConcreteStrategyC implements Strategy {
    
        @Override
        public void interfaceStrategy() {
            //相关的业务
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    2、Demo 测试
    public class Client {
    
        public static void main(String[] args) {
    
            // 模拟业务参数
            String parameter = "A";
    
            // 执行使用A策略
            Context context1 = new Context(new ConcreteStrategyA());
            context1.contextInterface();
            // 执行使用B策略
            Context context2 = new Context(new ConcreteStrategyB());
            context2.contextInterface();
            // 执行使用C策略
            Context context3 = new Context(new ConcreteStrategyB());
            context3.contextInterface();
    
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    三、策略模式的应用(Comparator 中的策略模式)

    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 接口中必须要子类实现的一个方法。

  • 相关阅读:
    dvwa 代码注入impossible代码审计
    JQuery专题
    【Pandas总结】第二节 Pandas 的数据读取_pd.read_csv()的使用详解(非常全面,推荐收藏)
    github一些有趣的使用场景和基本使用方法
    论文推荐:使用带掩码的孪生网络进行自监督学习
    js knex基本用法
    prometheus:(二)监控概述(你永远逃不出我的手掌哈哈)
    复现一个循环以及俩个循环问题
    Excel数据库中FullJion功能的实现
    《深入浅出.NET框架设计与实现》笔记6.3——ASP.NET Core应用程序多种运行模式之三——桌面应用程序
  • 原文地址:https://blog.csdn.net/weixin_45187434/article/details/128143313