Home > Java > javaTutorial > Han Xin's Become General: Delegation Mode

Han Xin's Become General: Delegation Mode

Release: 2023-08-25 15:55:30
forward
1317 people have browsed it

Hello everyone, I am Lao Tian. Starting from today, this official account will give you benefits every week. What should I give? It must be a technical book, not that many bells and whistles. See the end of the article for how to participate.

Okay, let’s get into our topic. Today I will share with you the Delegation pattern in the design pattern. Use appropriate life stories and real project scenarios to talk about the design pattern, and finally summarize the design pattern in one sentence.

Story

In the literal sense, delegation: refers to entrustment arrangement; delegation dispatch.

There is a model in our technical field also called the delegation model, but the delegation model does not belong to the 23 models of GOF. However, due to its nature and role, everyone summarizes the delegation model in the behavioral model.

Han Xin's Become General: Delegation Mode


In the Legend of Chu-Han, when Liu Bang made Han Xin a general, many people below were very dissatisfied. . The reason for his dissatisfaction is very simple, that is, Han Xin has not established many military projects and has no prestige in the team. However, he said bluntly: "I only obey the king's orders. I only want 10 generals who obey my orders."

Han Xin's Become General: Delegation Mode


Liu Bang issued orders to Han Xin, and Han Xin issued corresponding orders based on the generals' specialties.

Definition of delegation pattern

Delegation pattern: English Delegate Pattern, its basic function is to be responsible for task scheduling and assignment of tasks .

It should be noted here that the delegation mode is very similar to the proxy mode. The delegation mode can be regarded as a full authority of the static proxy in a special case.

Agent mode: The focus is on the process. Delegation model: The focus is on results.

Life Cases

In the company, the boss assigns tasks to the project manager, but the project manager himself does not know how to Instead of working, these tasks are handed over to the corresponding development colleagues according to the modules that each person is responsible for. Everyone tells the project manager the results of the task completion, and finally the project manager summarizes the results to the boss.

Here is a very typical application scenario of delegation mode.

Use a picture to represent:

Han Xin's Become General: Delegation Mode


##Code implementation

There are many development colleagues, but they have a unified attribute, which is the code:

//开发的同事进行抽象
public interface IEmployee {
    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 EmployeeC implements IEmployee {
    @Override
    public void doing(String command) {
        System.out.println("我是员工C,擅长做业务,现在开始做" + command);
    }
}
Copy after login

If we have employees, then we will define the project manager Leader.

import java.util.HashMap;
import java.util.Map;

public class Leader {

    private Map<String, IEmployee> employeeMap = new HashMap<>();
    //既然是项目经历,那他心里,肯定知道每个开发同事擅长的领域是什么
    public Leader() {
        employeeMap.put("数据库设计", new EmployeeA());
        employeeMap.put("架构设计", new EmployeeB());
        employeeMap.put("业务代码", new EmployeeC());
    }

    //leader接收到老板Boss的任务命令后
    public void doing(String command) {
        //项目经理通过任务命令,找到对应的开发同事,
        // 然后把对应任务明给这位同事,这位同事就可以去干活了
        employeeMap.get(command).doing(command);
    }
}
Copy after login

With development colleagues and project managers, there must also be a Boss.

public class Boss {
    //Boss也得根据每个项目经理锁负责的领域进行任务分配
    public void command(String command, Leader leader) {
        leader.doing(command);
    }
}
Copy after login

Test class:

public class DelegateDemoTest {
    public static void main(String[] args) {
        new Boss().command("架构设计", new Leader());
    }
}
Copy after login

Running result:

我是员工B,擅长做架构,现在开始做架构设计
Copy after login

In this way, we have implemented a case of delegation mode in life using code. Is it simple?

In the above case, there are three important roles:

  • 抽象人物角色IEmployee
  • 具体任务角色:EmployeeA、EmployeeB、EmployeeC
  • 委派这角色:Leader

真实应用场景

在Spring MVC中有个大姐耳熟能详的DispatcherServlet ,下面请看DispatcherServlet 在整个流程中的角色:

protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception {
    //转发、分派
    doDispatch(request, response);
}
/**
 * Process the actual dispatching to the handler.
 * 处理实际分派给处理程序
 * <p>The handler will be obtained by applying the servlet&#39;s HandlerMappings in order.
 * The HandlerAdapter will be obtained by querying the servlet&#39;s installed HandlerAdapters
 * to find the first that supports the handler class.
 * <p>All HTTP methods are handled by this method. It&#39;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 {
    ...
}
Copy after login

这里只能点到为止,因为涉及到很多东西,尤其是HandlerAdapters、HandlerMapping不是一时半会能讲完的。

另外, 在一些框架源码中,比如Spring等,命名以Delegate结尾,比如:BeanDefinitionParserDelegate(根据不同的类型委派不同的逻辑解析BeanDefinition),或者是以Dispacher开头和结尾或开头的,比如:DispacherServlet一般都使用了委派模式。

Advantages and disadvantages of delegation model

  • ##Advantages: Through task delegation, a large task can be Refinement, and then achieving task follow-up by unified management of the completion of these sub-tasks can speed up task completion.
  • Disadvantages: The task delegation method needs to be changed according to the complexity of the task. When the task is relatively complex, multiple delegations may be required, which can easily cause confusion.

Summary

Okay, that’s it for the delegation model, you learn Yet?

Finally, use one sentence to summarize the delegation model:

The requirements are very simple, but I don’t care

The above is the detailed content of Han Xin's Become General: Delegation Mode. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:Java后端技术全栈
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template