架构探险笔记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参数。这样的框架更加灵活,从使用的角度来看也更加完美。

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

 

转载于:https://www.cnblogs.com/aeolian/p/10108401.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值