search
HomeJavajavaTutorialHan Xin's Become General: Delegation Mode

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);
    }
}

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);
    }
}

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);
    }
}

Test class:

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

Running result:

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

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 {
    ...
}

这里只能点到为止,因为涉及到很多东西,尤其是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!

Statement
This article is reproduced at:Java后端技术全栈. If there is any infringement, please contact admin@php.cn delete
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools