策略模式和SpringMVC

2019-02-22  本文已影响3人  黄靠谱

概述

解决的问题:降低代码冗余度。

适用的业务场景:同一类型业务的类,有很多公用的流程和方法,只是在核心方法上略有区别,为了降低代码的冗余度,单独把不同的方法抽象成一个接口,各自业务类实现自己的核心方法。

比如在Spring MVC中,有4种类似的Handler类,抽象成一个HandlerAdapter接口,业务类根据自己的特点,执行各自的handler()方法。最终降低代码冗余度,可维护性提高。

源码分析

DispatcherServlet.doDispatch

protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
    ModelAndView mv = null;

    // Determine handler for the current request.
    mappedHandler = getHandler(processedRequest);

    // Determine handler adapter for the current request.
    HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());

    // Actually invoke the handler.
    mv = ha.handle(processedRequest, response, mappedHandler.getHandler());

    applyDefaultViewName(processedRequest, mv);
    mappedHandler.applyPostHandle(processedRequest, response, mv);
    processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);
    
}

HandlerAdapter 代表的不同类型的Handler们


image
上一篇下一篇

猜你喜欢

热点阅读