Let's talk about the delegation pattern of design patterns

The code farmer is on his way

Everyone is talking about opportunities, opportunities, choices, but to be able to meet the wind and seize the opportunity, the premise of making choices is that you have to have this ability, otherwise, even if you really encounter it, there is nothing you can do, and any success will go through Countless attempts, hard work, and failures. Only after experiencing these can you judge the trend, have the ability to seize opportunities, and have the thinking to distinguish choices. Otherwise, there is a high probability that you will be cannon fodder. Maybe what you do today is seen by others, even in the You seem to be all useless, but in fact it is not. It has been subtly changing itself, forging itself, and one day in the future, it will burst out with amazing power. Come on! Sao Nian

foreword

In real life, the word delegation can be seen everywhere. For example, when I graduated from high school, I worked as a salesman in a chain bridal shop. The other day I went out to hand out flyers and find someone to take wedding photos. After working for a few days, The female second-in-command told me that the superior boss arranged to sort out the information and needed an employee to sort it out. She said she thought I was cute, so she asked me to sort it out. Obviously, she didn’t want to sort it out herself, so she asked me to sort it out. Under the eaves, how could anyone not bow their heads, so I sorted it out with tears in my eyes, but after working for a while, I couldn't stand the atmosphere, so I ran away with a bucket overnight.

From this experience of mine, we can see that there are layers of entrustment between people at different levels, and finally it falls to me, a lower-level person. Later, I am often entrusted by superiors when I participate in work.

Delegated mode coding implementation

Use code to implement task delegation between leaders and employees. The boss arranges tasks. After the department manager receives the order, he delegates the corresponding employees to do things.

task interface

Define a task interface, define a method dispatch(), and implement it by a specific employee.

/**
 * @author 刘牌
 * @date 2022/3/12 2:18
 */
public interface ITask {
    void dispatch(String task);
}
复制代码

Department Manager Delegated Class

The department manager is the delegator. Its function is to sort out the characters and distribute them to the corresponding employees. He uses a Map structure to store them. The key is the task name, and the value is the specific implementer (employee). The passed key Get the corresponding implementer and call the corresponding implementation method.

/**
 * @author 刘牌
 * @date 2022/3/12 2:22
 */
public class DeptLeader implements ITask {
    private final Map<String, ITask> staffTaskMap = new HashMap<>();

    public DeptLeader() {
        staffTaskMap.put("整理资料",new StaffLiu());
        staffTaskMap.put("收集资料",new StaffZhang());
        staffTaskMap.put("传送资料",new StaffLi());
    }

    @Override
    public void dispatch(String task) {
        if (staffTaskMap.containsKey(task)) staffTaskMap.get(task).dispatch(task);
    }
}
复制代码

Employee specific task class

Employees are to do specific tasks. Three employees are entrusted to do things. Employee Liu organizes information, employee Zhang mobile phone information, and employee Li transmits information. What they have to do is not up to them. It is absolutely up to the department leader. In real life, if the boss asks you to organize If you say you don't want to sort out the data, you want to sweep the floor, then you should stay here for a while.

/**
 * @author 刘牌
 * @date 2022-04-0622:37
 */
public class StaffLi implements ITask{
    @Override
    public void dispatch(String task) {
        System.out.println("员工李被委派:"+task);
    }
}

public class StaffLiu implements ITask {
    @Override
    public void dispatch(String task) {
        System.out.println("员工刘被委派:"+task);
    }
}

public class StaffZhang implements ITask {
    @Override
    public void dispatch(String task) {
        System.out.println("员工张被委派:"+task);
    }
}
复制代码

Boss issues commands

Boss issues orders to sort out data, orders are first issued to department managers, and then department managers are issued to specific employees.

/**
 * @author 刘牌
 * @date 2022/3/12 2:28
 */
public class BossClient {
    public static void main(String[] args) {
        DeptLeader deptLeader = new DeptLeader();
        deptLeader.dispatch("整理资料");
    }
}
复制代码

output

员工刘被委派:整理资料
复制代码

到这里,一个简单委派模式的例子就完成了,比较简单。

思考

从上面的例子中我们发现委派是不是核代理模式很像,代理模式的思想就是自己不做具体的任务,让别人去做,委派模式也是一样,自己不做具体的任务, 而是委派给其他人来做,区别在于,在委派者这里,它由多种策略组成,根据不同的指令,选择不同的策略,所以,委派模式也是策略模式的思想,那么 综合一个,委派模式就是代理模式和策略模式的组合。

使用场景

那么我们在哪里使用委派模式呢?如果我们的系统中有很多类,它们的定义一样,都是相同的架子,只是处理方式不一样,需要根据不同的请求来调用不同 的类,那么可以选择委派模式,委派模式也能够很好的解耦系统代码,因为具体的任务让具体的类去实现,不用集中处理,当新增加任务,只需要增加相应 的实现类即可。

在一些开源框架和JDK中,也用到了委派模式,JDK双亲委派机制就是委派模式的思想,我们知道知道,JDK中加载一个类,会使用ClassLoader进行加载, 分为三个类加载器,启动类加载器Bootstrap ClassLoader,扩展类加载器Extension ClassLoader,应用程序类加载器Application ClassLoader 当我们加载一个类的时候,首先先去启动类加载器bootstrap找,如果有就直接用,如果没有就去扩展类加载器找,如果扩展类加载器没有,就去应用程序加载器找,如果还是没有,就报ClassNotFoundException异常。在SpringMVC中也是使用了委派模式,后面说SpringMVC的时候会详细说到。

今天的分享就到这里,感谢你的观看,我是小四,我们下期见。

Guess you like

Origin juejin.im/post/7083520892277358623