The design pattern under Linux-Delegate Pattern (Delegate Pattern) explained in simple terms [Recommended for novice collection]

Preface : Learning objectives: streamline program logic and improve code readability. Content positioning: people who hope to write more elegant code through learning the delegation model.

1. Definition of delegation mode

  1. The basic function of the delegate pattern is to be responsible for task scheduling and task assignment. It is very similar to the agent pattern, which can be regarded as a full-power agent of a static agent under special circumstances, but the delegate pattern focuses on the process, while the delegate pattern focuses on result.
  2. Not one of the design patterns in GOF 23
  3. Behavioural model

2. Common application scenarios

  • DispatcherServlet
  • The class name ends with Delegate
  • Including Dispatcher is generally a delegation mode
  • BeanDefinitionParserDelegate in Spring Framework IOC: Spring provides a variety of ways (java, xml, annotations) to configure beans, this class is responsible for distribution processing, and the injected bean information will eventually be loaded as a BeanDefition object (description object information)

Application scenario : Solve multi-tasks, and do not want to let users know about these tasks or specific implementations (do not let users directly interact), create an intermediate class, realize full authority, and achieve the purpose of having only one entry for users.

Three, simple code case

Example : The boss needs to assign tasks to employees, but he can't directly let the boss understand each employee's good function. You can create an intermediate manager position to understand the staff's expertise and distribute tasks.

boss

public class Boss {
    
    

    /**
     * 发任务
     * @param command
     * @param leader
     */
    public void command(String command,Leader leader){
    
    
        leader.doing(command);
    }
}

Manager

public class Leader {
    
    
//    预先知道每个员工的特长、特征,分发任务
    private Map<String,IEmployee> register = new HashMap<String,IEmployee>();

    public Leader(){
    
    
        register.put("加密",new EmployeeA());
        register.put("架构",new EmployeeB());
    }

    public void doing(String command){
    
    
//        交给指定的员工去做
        register.get(command).doing(command);
    }
}

Employee interface

public interface IEmployee {
    
    

    /**
     * 做事
     * @param command
     */
    void doing(String command);
}

Employee A

public class EmployeeA implements IEmployee {
    
    
    @Override
    public void doing(String command) {
    
    
        System.out.println("我是员工A,我开始干活了,我擅长加密,执行");
    }
}

Employee B

public class EmployeeB implements IEmployee {
    
    
    @Override
    public void doing(String command) {
    
    
        System.out.println("我是员工B,我擅长架构,我开始干活了");
    }
}

Test class

public class DelegateTest {
    
    

    public static void main(String[] args) {
    
    
        new Boss().command("架构",new Leader());
    }
}

Four, SpringMvc's DispatcherServlet simple implementation

DispatcherServlet is an implementation of the front controller delegation model, providing a centralized access point for Spring Web MVC and responsible for the assignment of responsibilities

web.xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>

  <servlet>
    <servlet-name>delegateServlet</servlet-name>
    <servlet-class>com.zc.pattern.delegate.mvc.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>delegateServlet</servlet-name>
    <url-pattern>/*</url-pattern>
  </servlet-mapping>

<!--  http://localhost:8080/getMemberById.do -->

</web-app>

DispatcherServlet

package com.zc.pattern.delegate.mvc;

import com.zc.pattern.delegate.mvc.controllers.MemberController;
import com.zc.pattern.delegate.mvc.controllers.OrderController;
import com.zc.pattern.delegate.mvc.controllers.SystemController;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class DispatcherServlet extends HttpServlet {
    
    

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
//        完成调度
        doDispach(req,resp);
    }

    private void doDispach(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    
    
        String uri = req.getRequestURI();
        if ("getMemberById".equals(uri)){
    
    
            String mid = req.getParameter("mid");
            new MemberController().getMemberById(mid);
        }else if ("getOrderById".equals(uri)){
    
    
            String oid = req.getParameter("oid");
            new OrderController().getOrderById(oid);
        }else if ("getSystemById".equals(uri)){
    
    
            new SystemController().logout();
        }else {
    
    
            resp.getWriter().write("404 not found");
        }
    }
}

MemberController


public class MemberController {
    
    

    public void getMemberById(String mid){
    
    
        System.out.println("获取员工id");
    }
}

OrderController


public class OrderController {
    
    

    public void getOrderById(String oid){
    
    
        System.out.println("获取订单id");
    }
}

SystemController


public class SystemController {
    
    

    public void logout(){
    
    
        System.out.println("退出");
    }
}

In order to thank you for your attention and support, this time I prepared a limited time to receive benefits: Ali interview questions, Baidu interview questions, Didi interview questions, Huawei interview questions, JD interview questions, Meituan interview questions, Tencent interview questions, headline interview questions , ZTE interview questions.
Insert picture description here
What are you waiting for? I recommend my linuxC/C++ language exchange group: [ 1106675687 ] I have compiled some learning books and video materials that I think are better to share in the group files, and you can add them if you need them! The top 100 enter the group to receive, an extra copy of C/C++, linux materials worth 199 is included (video tutorials, e-books, actual combat projects and codes), the following part is displayed.

Insert picture description here
Insert picture description here

Guess you like

Origin blog.csdn.net/m0_50662680/article/details/112471843