Table of Contents
真实应用场景 " >真实应用场景
Home Java javaTutorial Han Xin's Become General: Delegation Mode

Han Xin's Become General: Delegation Mode

Aug 25, 2023 pm 03:55 PM
java

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!

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

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)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Random Number Generator in Java Random Number Generator in Java Aug 30, 2024 pm 04:27 PM

Guide to Random Number Generator in Java. Here we discuss Functions in Java with examples and two different Generators with ther examples.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

See all articles