委派模式

一.委派模式

委派模式:负责任务的调度和分配任务,也就是当任务下来了,找人干活!

二.委派模式-示例

1.新建一IExecute接口,用于下发命令

public interface IExecute {

    public void execute(String cmd);
}

2.新建一员工A类实现IExecute接口-进行命令的具体实现-只会削苹果

// 该员工只会削苹果
public class EmployeeA implements IExecute {
    @Override
    public void execute(String cmd) {
        System.out.println("员工A"+cmd);
    }
}

3.新建一员工B类实现IExecute接口-进行命令的具体实现-只会削梨子

// 员工B只会削梨子
public class EmployeeB implements IExecute {
    @Override
    public void execute(String cmd) {
        System.out.println("员工B"+cmd);
    }
}

4.新建一领导类实现IExecute接口-进行命令委派

public class Leader implements IExecute{

    // 存储 命令-员工 之间的关系
    private Map map = new HashMap<>();

    public Leader() {
        // 让员工A--削苹果
        map.put("削苹果",new EmployeeA());
        // 让员工B--削梨子
        map.put("削梨子",new EmployeeB());
    }

    @Override
    public void execute(String cmd) {
        if(map.containsKey(cmd)){
            // 根据命令,找到合适的员工,进行执行
            map.get(cmd).execute(cmd);
        }else{
            System.out.println("没有找到可以["+cmd+"]的员工!--需要联系HR进行招聘");
        }
    }
}

5.新建一测试类

public class Test {
    public static void main(String[] args) {
        Leader l = new Leader();
        l.execute("削苹果");
        l.execute("削梨子");
        l.execute("剥桔子");
    }
}

6.结果

委派模式_第1张图片

7.关系类图

委派模式_第2张图片

三.委派模式-在Spring源码中的示例-DispatcherServlet

1.精简后的DispatcherServlet源码

package org.springframework.web.servlet;

/***/

public class DispatcherServlet extends FrameworkServlet {

    /***/
    
    private List handlerMappings;

    /***/

    public DispatcherServlet() {
        this.setDispatchOptionsRequest(true);
    }

    public DispatcherServlet(WebApplicationContext webApplicationContext) {
        super(webApplicationContext);
        this.setDispatchOptionsRequest(true);
    }

    /***/
    
    private void initHandlerMappings(ApplicationContext context) {
        this.handlerMappings = null;
        if (this.detectAllHandlerMappings) {
            Map matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerMapping.class, true, false);
            if (!matchingBeans.isEmpty()) {
                this.handlerMappings = new ArrayList(matchingBeans.values());
                AnnotationAwareOrderComparator.sort(this.handlerMappings);
            }
        } else {
            try {
                HandlerMapping hm = (HandlerMapping)context.getBean("handlerMapping", HandlerMapping.class);
                this.handlerMappings = Collections.singletonList(hm);
            } catch (NoSuchBeanDefinitionException var3) {
                ;
            }
        }

        if (this.handlerMappings == null) {
            this.handlerMappings = this.getDefaultStrategies(context, HandlerMapping.class);
            if (this.logger.isDebugEnabled()) {
                this.logger.debug("No HandlerMappings found in servlet '" + this.getServletName() + "': using default");
            }
        }

    }

    /***/

    // 通过doDispatch进行请求的转发
    protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpServletRequest processedRequest = request;
        HandlerExecutionChain mappedHandler = null;
        boolean multipartRequestParsed = false;
        WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);

        try {
            try {
                ModelAndView mv = null;
                Object dispatchException = null;

                try {
                    processedRequest = this.checkMultipart(request);
                    multipartRequestParsed = processedRequest != request;
                    // 通过getHandler去获取,请求所对应的执行链
                    mappedHandler = this.getHandler(processedRequest);
                    if (mappedHandler == null || mappedHandler.getHandler() == null) {
                        this.noHandlerFound(processedRequest, response);
                        return;
                    }

                    // 通过getHandlerAdapter获取所执行的方式
                    HandlerAdapter ha = this.getHandlerAdapter(mappedHandler.getHandler());
                    String method = request.getMethod();
                    boolean isGet = "GET".equals(method);
                    if (isGet || "HEAD".equals(method)) {
                        long lastModified = ha.getLastModified(request, mappedHandler.getHandler());
                        if (this.logger.isDebugEnabled()) {
                            this.logger.debug("Last-Modified value for [" + getRequestUri(request) + "] is: " + lastModified);
                        }

                        if ((new ServletWebRequest(request, response)).checkNotModified(lastModified) && isGet) {
                            return;
                        }
                    }

                    if (!mappedHandler.applyPreHandle(processedRequest, response)) {
                        return;
                    }

                    // 通过mappedHandler.getHandler()==>获取我们所执行的方法(也就是对应的@RequestMapping注解所在的方法)
                    // 通过HandlerAdapter匹配的对应的执行方式去执行,获得ModelAndView执行返回
                    mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
                    if (asyncManager.isConcurrentHandlingStarted()) {
                        return;
                    }

                    this.applyDefaultViewName(processedRequest, mv);
                    mappedHandler.applyPostHandle(processedRequest, response, mv);
                } catch (Exception var20) {
                    dispatchException = var20;
                } catch (Throwable var21) {
                    dispatchException = new NestedServletException("Handler dispatch failed", var21);
                }

                this.processDispatchResult(processedRequest, response, mappedHandler, mv, (Exception)dispatchException);
            } catch (Exception var22) {
                this.triggerAfterCompletion(processedRequest, response, mappedHandler, var22);
            } catch (Throwable var23) {
                this.triggerAfterCompletion(processedRequest, response, mappedHandler, new NestedServletException("Handler processing failed", var23));
            }

        } finally {
            if (asyncManager.isConcurrentHandlingStarted()) {
                if (mappedHandler != null) {
                    mappedHandler.applyAfterConcurrentHandlingStarted(processedRequest, response);
                }
            } else if (multipartRequestParsed) {
                this.cleanupMultipart(processedRequest);
            }

        }
    }

   /***/

    protected HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
        Iterator var2 = this.handlerMappings.iterator();

        HandlerExecutionChain handler;
        do {
            if (!var2.hasNext()) {
                return null;
            }

            HandlerMapping hm = (HandlerMapping)var2.next();
            if (this.logger.isTraceEnabled()) {
                this.logger.trace("Testing handler map [" + hm + "] in DispatcherServlet with name '" + this.getServletName() + "'");
            }

            // 会通过请求中的路径,去匹配到(我们通过@RequestMapping注解所在的方法)
            handler = hm.getHandler(request);
        } while(handler == null);

        return handler;
    }

    /***/

}

2.对与Spring源码DispatcherServlet-进行粗糙的仿写

1.新建一DispatcherServlet

public class DispatcherServlet {
    private List handlerMappings;
    private void initHandlerMappings() {
        this.handlerMappings = new ArrayList<>();
        this.handlerMappings.add(new HandlerMapping("login",new Handler("login()","loginSuccess")));
        this.handlerMappings.add(new HandlerMapping("logout",new Handler("logout()","logoutSuccess")));
    }

    public DispatcherServlet() {
        initHandlerMappings();
    }

    protected void doDispatch(String request){
        Handler handler = this.getHandler(request);
        System.out.println("执行方法["+handler.getName()+"],获得结果["+handler.getResult()+"]");
    }

    private Handler getHandler(String request){
        Iterator var2 = this.handlerMappings.iterator();

        Handler handler;
        do {
            if (!var2.hasNext()) {
                return null;
            }

            HandlerMapping hm = (HandlerMapping)var2.next();

            handler = hm.getHandler(request);
        } while(handler == null);

        return handler;
    }
}

2.新建一HandlerMapping

public class HandlerMapping {

    private String method;

    private Handler handler;

    public HandlerMapping(String method, Handler handler) {
        this.method = method;
        this.handler = handler;
    }

    public Handler getHandler(String request){
        if (request.equals(this.method)){
            return this.handler;
        }
        return null;
    }
}

3.新建一handler

public class Handler {

    private String name;

    private String result;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getResult() {
        return result;
    }

    public void setResult(String result) {
        this.result = result;
    }

    public Handler(String name, String result) {
        this.name = name;
        this.result = result;
    }
}

4.新建一测试类

public class Test {
    public static void main(String[] args) {
        DispatcherServlet dispatcherServlet = new DispatcherServlet();
        dispatcherServlet.doDispatch("login");
        dispatcherServlet.doDispatch("logout");
    }
}

5.测试结果

委派模式_第3张图片 

6.DispatcherServlet类图

委派模式_第4张图片

你可能感兴趣的:(设计模式)