委派模式
委派模式(Delegate Pattern)不属于GoF23中设计模式。
委派模式的基本作用就是负责任务的调用个分配,和代理模式相似但是代理模式注重过程而委派模式注重的是结果
委派模式在spring中应用的非常多,比如我们熟悉的DispatcherServlet
老板给项目经理下达任务,项目经理会根据实际情况把任务分配给每一个员工,等员工完成任务,再由项目经理向老板汇报
这里的项目经理就是老板委派帮自己干活的人
具体实现
public interface IEmployee {
public void doing(String command);
}
public class EmployeeA implements IEmployee {
@Override
public void doing(String command) {
System.out.println("我是员工A,我开始干"+command+"工作");
}
}
public class EmployeeB implements IEmployee {
@Override
public void doing(String command) {
System.out.println("我是员工B,我开始干"+command+"工作");
}
}
public class Leader implements IEmployee{
private Map<String, IEmployee> targets = new HashMap<String, IEmployee>();
public Leader() {
targets.put("前端", new EmployeeA());
targets.put("后端", new EmployeeB());
}
@Override
public void doing(String command) {
// TODO Auto-generated method stub
targets.get(command).doing(command);
}
}
public class Boss {
public void command(String command,Leader leader) {
leader.doing(command);
}
}
public class DelegateTest {
public static void main(String[] args) {
new Boss().command("后端", new Leader());
}
}
----------------------------------------------------------------------
我是员工B,我开始干后端工作
----------------------------------------------------------------------
源码
DispatcherServlet类
All HTTP methods are handled by this method. It’s up to HandlerAdapters or handlers themselves to decide which methods are acceptable.
//由HandlerAdapters or handlers来决定哪些方法是可以处理的(说明HandlerAdapters or handlers被委派来处理这些事情)
/**
* Process the actual dispatching to the handler.
* <p>The handler will be obtained by applying the servlet's HandlerMappings in order.
* The HandlerAdapter will be obtained by querying the servlet's installed HandlerAdapters
* to find the first that supports the handler class.
* <p>All HTTP methods are handled by this method. It's up to HandlerAdapters or handlers
* themselves to decide which methods are acceptable.
* @param request current HTTP request
* @param response current HTTP response
* @throws Exception in case of any kind of processing failure
*/
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
HttpServletRequest processedRequest = request;
HandlerExecutionChain mappedHandler = null;
boolean multipartRequestParsed = false;
WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
try {
ModelAndView mv = null;
Exception dispatchException = null;
try {
processedRequest = checkMultipart(request);
multipartRequestParsed = (processedRequest != request);
// Determine handler for the current request.
mappedHandler = getHandler(processedRequest);
if (mappedHandler == null) {
noHandlerFound(processedRequest, response);
return;
}
// Determine handler adapter for the current request.
HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
// Process last-modified header, if supported by the handler.
String method = request.getMethod();
boolean isGet = "GET".equals(method);
if (isGet || "HEAD".equals(method)) {
long lastModified = ha.getLastModified(request, mappedHandler.getHandler());
if (logger.isDebugEnabled()) {
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;
}
// Actually invoke the handler.
mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
if (asyncManager.isConcurrentHandlingStarted()) {
return;
}
applyDefaultViewName(processedRequest, mv);
mappedHandler.applyPostHandle(processedRequest, response, mv);
}
catch (Exception ex) {
dispatchException = ex;
}
catch (Throwable err) {
// As of 4.3, we're processing Errors thrown from handler methods as well,
// making them available for @ExceptionHandler methods and other scenarios.
dispatchException = new NestedServletException("Handler dispatch failed", err);
}
processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);
}
catch (Exception ex) {
triggerAfterCompletion(processedRequest, response, mappedHandler, ex);
}
catch (Throwable err) {
triggerAfterCompletion(processedRequest, response, mappedHandler,
new NestedServletException("Handler processing failed", err));
}
finally {
if (asyncManager.isConcurrentHandlingStarted()) {
// Instead of postHandle and afterCompletion
if (mappedHandler != null) {
mappedHandler.applyAfterConcurrentHandlingStarted(processedRequest, response);
}
}
else {
// Clean up any resources used by a multipart request.
if (multipartRequestParsed) {
cleanupMultipart(processedRequest);
}
}
}
}