[Turn] spring common mode -------- delegate mode

https://www.jianshu.com/p/38acf37b1e1f

1. Introduction Delegate mode

In the commonly used 23 kinds of design patterns actually face no shadow delegate mode (delegate), but the pattern is really delegated more of a model used in the Spring.

Reflected in the spring: Spring MVC framework DispatcherServlet fact used the delegate model.

Delegate role model: the basic role is responsible for the task of calls and assigning tasks, like with proxy mode, can be seen as a static proxy at a special case of sole agent, but the agent model focuses on process rather delegate model focuses on results

Example 2. Mode delegated

Quote from a map to introduce delegated mode, the following figure illustrates the main task of the boss to leader, and leader did the job allocation and scheduling of a task, he did not do the work, but the specific work to specific executor do it.

Delegate mode .png

The following examples are given direct:

Interface Execution

/**
 * @Project: spring
 * @description: 执行的接口
 * @author: sunkang
 * @create: 2018-08-30 23:10
 * @ModificationHistory who      when       What
 **/
public interface IExcuter {
    void excute(String command);
}

A general staff

/**
 * @Project: spring
 * @description: 员工A执行某项命令
 * @author: sunkang
 * @create: 2018-08-30 23:10
 * @ModificationHistory who      when       What
 **/
public class ExcuterA implements  IExcuter{

    @Override
    public void excute(String command) {
        System.out.println("员工A 开始做"+command+"的工作");
    }
}

B ordinary employees

/**
 * @Project: spring
 * @description: 员工B执行某项命令
 * @author: sunkang
 * @create: 2018-08-30 23:10
 * @ModificationHistory who      when       What
 **/
public class ExcuterB implements  IExcuter{
    @Override
    public void excute(String command) {
        System.out.println("员工B 开始做"+command+"的工作");
}
}

leader delegator

/**
 * @Project: spring
 * @description:    leader 委派者   任务分发的作用
 * @author: sunkang
 * @create: 2018-08-30 23:11
 * @ModificationHistory who      when       What
 **/
public class Leader implements  IExcuter {

    private Map<String,IExcuter> targets = new HashMap<String,IExcuter>();
    public Leader() {
        targets.put("加密",new ExcuterA());
        targets.put("登录",new ExcuterB());
    }
    @Override
    public void excute(String command) {
        targets.get(command).excute(command);
    }
}

boss class simulation test call

/**
 * @Project: spring
 * @description:  boss  模拟客户执行任务
 * @author: sunkang
 * @create: 2018-08-30 23:13
 * @ModificationHistory who      when       What
 **/
public class Boss
{
    public static void main(String[] args) {
        Leader leader  = new Leader();
        //看上去好像是我们的项目经理在干活
        //但实际干活的人是普通员工
        //这就是典型,干活是我的,功劳是你的
        leader.excute("登录");
        leader.excute("加密");
    }
}

Test results:

Delegate mode test results .png

3. A simple example implementation of delegation mode mvc

Question:
In springmvc 访问地址的urland Controller层配置的urlhow mapped
Controller layer 配置的urlhow with the 具体的方法map, 参数and how 绑定the

Guess:
url address can be obtained according to request access url address, url address can be configured according to the configuration notes, both matching the description url mapping is successful, in addition url is not enough, you also need an intermediate object to save the url controller and method and an information object may be mapped to the middle-aged objects into the container, then removed from the container matches the passed url, it can be done according to mapping method is invoked after taken out.

Here a simple example of the realization of a call mvc
analog controller layer

/**
 * @Project: spring
 * @description:  模拟controller层
 * @author: sunkang
 * @create: 2018-09-03 22:20
 * @ModificationHistory who      when       What
 **/
public class MemberAction {

    public void getMemberById(String mid){
        
    }
}

How to simulate serlvert obtained forwarding request, to a particular process controller

/**
 * @Project: spring
 * @description:   selvelt的任务分发者 ,主要完成url的映射和调用
 * @author: sunkang
 * @create: 2018-09-03 22:21
 * @ModificationHistory who      when       What
 **/
public class SelvletDispatcher {
    //这里也可以用map 对象来保存Hanlder对象
    private List<Handler> handlerMapping = new ArrayList<Handler>();
    
    public SelvletDispatcher() {
        //简单实现一个controller的映射
        try {
      Class clazz  = MemberAction.class;

            handlerMapping.add(new Handler()
                            .setController(clazz.newInstance())
                            .setMethod(clazz.getMethod("getMemberById",new Class[]{String.class}))
                            .setUrl("/web/getMemberById.json")
            );
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void  doService(HttpServletRequest request, HttpServletResponse response){
        doDispatch(request,response);
    }

    /**
     * 请求的分发工作
     * @param request
     * @param response
     */
    private void doDispatch(HttpServletRequest request, HttpServletResponse response) {
      //1.获取用户请求的url
      String uri =   request.getRequestURI();
      Handler handler =null;

      ////2、根据uri 去handlerMapping找到对应的hanler
      for(Handler h :handlerMapping){
          if(uri.equals(h.getUrl())){
              handler = h;
              break;
          }
      }
      //3.将具体的任务分发给Method(通过反射去调用其对应的方法)
        Object obj = null;
        try {
            obj =  handler.getMethod().invoke(handler.getController(),request.getParameter("mid"));
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        //4、获取到Method执行的结果,通过Response返回出去
        // response.getWriter().write();

    }
    /**
     * 具体的hanlder对象
     */
    class Handler{
        //controller对象
        private Object controller;
        //controller对象映射的方法
        private  String url;
        //ulr对应的方法
        private Method method;

        public Object getController() {
            return controller;
        }

        public Handler setController(Object controller) {
            this.controller = controller;
            return this;
        }

        public String getUrl() {
            return url;
        }

        public Handler setUrl(String url) {
            this.url = url;
            return  this;
        }

        public Method getMethod() {
            return method;
        }

        public Handler setMethod(Method method) {
            this.method = method;
            return this;
        }
    }
}

Guess you like

Origin blog.csdn.net/kingdelee/article/details/85147953