zoukankan      html  css  js  c++  java
  • SpringBoot使用策略模式+工厂模式

    为了防止大量的if...else...switch case代码的出现,可以使用策略模式+工厂模式进行优化。
    在我的项目当中,报表繁多,所以尝试了这种方式进行优化报表的架构。代码很简单,如下:

    Factory工厂类

    @Service
    public class ReportFactory {
    
        /**
         * 初始化的时候将所有的ReportService自动加载到Map中
         */
        @Autowired
        private final Map<String, ReportService> reportIns = new ConcurrentHashMap<>();
    
        public ReportService getReportIns(String code) {
            ReportService reportInstance = reportIns.get(code);
            if (reportInstance == null) {
                throw new RuntimeException("未定义reportInstance");
            }
    
            return reportInstance;
        }
    
    }
    

    接口

    public interface ReportService {
        String getResult();
    }
    

    实现类

    @Component(value = "A1")
    public class ReportServiceA1 implements ReportService {
    
        @Override
        public String getResult() {
            return "我是A1";
        }
    }
    
    @Component(value = "A2")
    public class ReportServiceA2 implements ReportService {
    
        @Override
        public String getResult() {
            return "我是A2";
        }
    }
    

    测试

    @SpringBootTest
    public class BlogServerApplicationTest {
    
        @Autowired
        ReportFactory reportFactory;
    
        @Test
        public void test2() {
            String result1 = reportFactory.getReportIns("A1").getResult();
            System.out.println("-----------------");
            System.out.println(result1);
            String result2 = reportFactory.getReportIns("A2").getResult();
            System.out.println("-----------------");
            System.out.println(result2);
        }
    }
    

    打印如下:

    -----------------
    我是A1
    -----------------
    我是A2
    

    总结

    在平时的工作当中,写一些业务代码是无可避免的,但是只要不局限于现状,往往可以发现不一样的乐趣。就像我在报表的业务中学习到了策略模式+工厂模式。

    个人博客网址: https://colablog.cn/

    如果我的文章帮助到您,可以关注我的微信公众号,第一时间分享文章给您
    微信公众号

  • 相关阅读:
    常用函数工具记录贴
    phpCAS::handleLogoutRequests()关于java端项目登出而php端项目检测不到的测试
    Cas服务器设置(java),java、php客户端配置
    android导入项目出现R文件不能生成
    Error executing aapt: Return code -1073741819
    网页在线播发视频 在线查看文档
    jeecg的cq查询方式
    威佐夫博弈
    HDU 1850 (尼姆博奕)
    HDU2149 (巴什博弈)
  • 原文地址:https://www.cnblogs.com/Johnson-lin/p/14028372.html
Copyright © 2011-2022 走看看