zoukankan      html  css  js  c++  java
  • 架构探险笔记9-框架优化之参数优化

    目前的框架已具备IOC、AOP、MVC等特性,基本上一个简单的WEB应用可以通过它来开发了。但或多或少还存在一些不足,需要优化的地方还很多,此外,还有一些更强大的功能需要不断地补充进来。

    优化Action参数

    明确Action参数优化目标

    对于某些Action方法,根本用不上Param参数,但框架需要我们必须提供一个Param参数,这样未免有些勉强。

        /**
         * 进入客户端界面
         */
        @Action("get:/customer")
        public View index(Param param){
            List<Customer> customerList = customerService.getCustomerList("");
            return new View("customer.jsp").addModel("customerList",customerList);
        }

    这个Action方法根本就不需要Param参数,放在这里确实有些累赘,我们得想办法去掉这个参数,并且确保框架能够成功地调用Action方法。

    动手优化Action参数使用方式

    修改框架代码来支持这个特性:

    @WebServlet(urlPatterns = "/*",loadOnStartup = 0)
    public class DispatcherServlet extends HttpServlet {
    
        @Override
        protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
                ***
                Param param = new Param(paramMap);
                //调用Action方法
                Method actionMethod = handler.getActionMethod();
                Object result = null;
                /*优化没有参数的话不需要写参数*/
                if (param.isEmpty()){  //如果没有参数
                    result = ReflectionUtil.invokeMethod(controllerBean,actionMethod);  //就不传参数
                }else{  //有参数
                    result = ReflectionUtil.invokeMethod(controllerBean,actionMethod,param);  //传参数
                }
                ***
        }
    }

    当param.isEmpty()为true时,可以不将Param参数传入Action方法中,反之则将Param参数传入Action方法中。

    因此,我们需要为Param类添加一个isEmpty()方法。

    public class Param {
        private Map<String,Object> paramMap;
    
        ***
    
        /**
         * 验证参数是否为空
         * @return
         */
        public boolean isEmpty(){
            return CollectionUtil.isEmpty(paramMap);
        }
    }

    所谓验证参数是否为空,实际上是判断Param中的paramMap是否为空。

    一旦做了这样的调整,我们就可以在Action方法中根据实际情况省略了Param参数了,就像这样

        /**
         * 进入客户端界面
         */
        @Action("get:/customer")
        public View index(){
            List<Customer> customerList = customerService.getCustomerList("");
            return new View("customer.jsp").addModel("customerList",customerList);
        }

    至此,Action参数优化完毕,我们可以根据实际情况自由选择是否在Action方法中使用Param参数。这样的框架更加灵活,从使用的角度来看也更加完美。

    提示:框架的实现细节也许比较复杂,但框架的创建者一定要站在使用者的角度,尽可能的简化框架的使用方法。注重细节并不断优化,这是每个框架创建者的职责。

  • 相关阅读:
    NEC的学习笔记
    MVC过滤器中获取实体类属性值
    Facebook Hack 语言 简介
    6.格式化输出(转)
    ProcessBuilder 和 Runtime(转)
    JAVA I/O使用方法(转)
    java中输出流OutputStream 类应用实例(转)
    InputStream、OutputStream、String的相互转换(转)
    海茶3 らぶデス3 入门经典教程
    天将降大任于斯人也,必先苦其心志,劳其筋骨,饿其体肤,空乏其身,行拂乱其所为,所以动心忍性,增益其所不能
  • 原文地址:https://www.cnblogs.com/aeolian/p/10108401.html
Copyright © 2011-2022 走看看