• 抽丝剥茧——策略设计模式


    策略设计模式

    哈喽,兄弟们好。今天我们来聊一下策略设计模式。

    兄弟们有没有写过这样的代码呢?

    if(){
        
    }else if(){
        
    }else if(){
        
    }else if(){
        
    }else if(){
        
    }else{
        
    }
    

    这样的代码往往在业务中的体现是:根据用户不同的身份进行特定的处理,不过随着系统的不断扩大,会导致代码变得越来越臃肿。所以我们需要学习以下策略模式来解决这样的问题。

    我们来看一下策略模式做了什么?

    策略模式最主要的特点是:将要执行的策略传入,体现在Java中就是传入一个接口的实现类,然后调用这个接口的方法,执行策略

    我们以上面的案例为背景进行讲解:假设现在要进行不同语言的打印输出效果

    传统方法:if,else判断传入的是什么语言,根据判断结果输出不同的效果

    策略模式:传入不同语言要执行的打印代码。比如,如果是Java则传入一个IPrintInteface的实现作为要执行的动作。

    我们代码解释一下:

    public class StrategyDesgin {
        public static void main(String[] args) {
            Java java = new Java();
            //将我们需要做的行为传入
            test(java);
        }
    
        public static void test(IPrintInterface printInterface){
            printInterface.print();
        }
    }
    
    
    class Java implements IPrintInterface{
    
        @Override
        public void print() {
            System.out.println("Java输出");
        }
    }
    
    class C implements IPrintInterface{
    
        @Override
        public void print() {
            System.out.println("C输出");
        }
    }
    
    class JavaScript implements IPrintInterface{
    
        @Override
        public void print() {
            System.out.println("JavaScript输出");
        }
    }
    
    interface IPrintInterface{
        void print();
    }
    

    我们前面聊过JDK1.8提供的Lambda表达式,它为我们书写策略模式提供了非常简单的写法,我们仍然以上述的场景为例,看一下代码实现。

    public class StrategyDesgin {
        public static void main(String[] args) {
            test(()-> System.out.println("Java输出"));
        }
    
        public static void test(IPrintInterface printInterface){
            printInterface.print();
        }
    }
    
    interface IPrintInterface{
        void print();
    }
    

    我们来总结一下:策略模式所做的事情就是将我们需要执行的行为传给函数,然后让函数执行,避免选择判断的过程。这就是策略设计模式的全部内容了。

  • 相关阅读:
    Groups And SiteGroups
    【objc】objectivec学习(1)
    【正则】正则表达式和自动机
    【android】ListView的item事件和item里面的view的事件同时存在
    【计划】rss,搜索
    【objc】Foundation Kit
    【设计】【爬虫】针对某一主题做的爬虫,使用Jsoup解析
    【java】【实践】阅读代码,一些较好的实践
    【java】【HtmlParser】HtmlParser使用
    【learn】learn1
  • 原文地址:https://www.cnblogs.com/onlyzuo/p/13904918.html
Copyright © 2020-2023  润新知