With so many groups of wechat and QQ, how should we manage the friend relationship?

Keywords: Java Design Pattern Back-end Programmer

This article is excerpted from "design patterns should be learned this way"

1. Application scenario of intermediary mode

In real life, the existence of intermediaries is indispensable. Without intermediaries, we can't communicate with distant friends. Each colleague object will reference each other. If each object interacts with multiple objects, a network structure will be formed as shown in the following figure.

As can be seen from the above figure, each object is over coupled, which is not conducive to information reuse or expansion. If the mediator pattern is introduced, the relationship between objects will become a star structure, as shown in the following figure.

As can be seen from the above figure, after using the mediator mode, the change of any class will only affect the mediator and the class itself. Unlike the previous design, the change of any class will cause the change of all its associated classes. This design greatly reduces the coupling of the system. In fact, the circle of friends we brush every day in our daily life is an intermediary. In addition, the information trading platform we see is also the embodiment of the intermediary model.

The mediator pattern is used to reduce the communication complexity between multiple objects and classes. By providing a mediation class, this model changes the many to many relationship between objects at all levels of the system into one to many relationship. The mediator object can change the complex network structure into a star structure centered on the mediator, so as to reduce the complexity of the system and improve the scalability. If there are a large number of association relationships between the objects at all levels of the system, that is, the hierarchical objects are in a complex network structure. If they are tightly coupled directly, the system structure will become extremely complex. When one of the hierarchical objects changes, the corresponding hierarchical objects tightly coupled with it also need to be modified, which is difficult for the system to maintain. In short, if multiple classes are coupled to form a network structure, consider using the mediator pattern for optimization. To sum up, the mediator model is mainly applicable to the following application scenarios.

(1) There are complex reference relationships between objects in the system, and the resulting interdependence structure is chaotic and difficult to understand.

(2) Interactive public behavior. If you need to change the behavior, you can add a new mediator class.

2 UML class diagram of mediator pattern

The UML class diagram of the mediator pattern is shown in the following figure.

3. Design group chat scenarios using mediator mode

Suppose we want to build a chat room system. Users can send messages to the chat room, and the chat room will display messages to all users. In fact, it is the communication process between the User sending the message and the chat room display. However, the User cannot directly send the message to the chat room, but needs to send the message to the server first, and then the server sends the message to the chat room for display. The specific code is as follows. First create the User class.

public class User {
    private String name;
    private ChatRoom chatRoom;

    public User(String name, ChatRoom chatRoom) {
        this.name = name;
        this.chatRoom = chatRoom;
    }

    public void sendMessage(String msg) {
        this.chatRoom.showMsg(this, msg);
    }

    public String getName() {
        return name;
    }
}

Then create the ChatRoom class.

public class ChatRoom {
    public void showMsg(User user, String msg) {
        System.out.println("[" + user.getName() + "] :" + msg);
    }
}

Finally, write the client test code.

public static void main(String[] args) {
        ChatRoom room = new ChatRoom();

        User tom = new User("Tom",room);
        User jerry = new User("Jerry",room);
        tom.sendMessage("Hi! I am Tom.");
        jerry.sendMessage("Hello! My name is Jerry.");
}

The operation results are shown in the figure below.

4 Application of mediator mode in JDK source code

First, let's look at the Timer class in the JDK. After opening the Timer structure, we find that there are many schedule() overloaded methods in the Timer class, as shown in the following figure.

Click any one of the methods, and we find that all the methods finally call the private schedule() method. The source code is as follows.

public class Timer {
    ...    
    public void schedule(TimerTask task, long delay) {
        if (delay < 0)
            throw new IllegalArgumentException("Negative delay.");
        sched(task, System.currentTimeMillis()+delay, 0);
    }
    ...
    private void sched(TimerTask task, long time, long period) {
        if (time < 0)
            throw new IllegalArgumentException("Illegal execution time.");

        if (Math.abs(period) > (Long.MAX_VALUE >> 1))
            period >>= 1;

        synchronized(queue) {
            if (!thread.newTasksMayBeScheduled)
                throw new IllegalStateException("Timer already cancelled.");

            synchronized(task.lock) {
                if (task.state != TimerTask.VIRGIN)
                    throw new IllegalStateException(
                        "Task already scheduled or cancelled");
                task.nextExecutionTime = time;
                task.period = period;
                task.state = TimerTask.SCHEDULED;
            }

            queue.add(task);
            if (queue.getMin() == task)
                queue.notify();
        }
    }
    ...
}

Moreover, no matter what kind of tasks are added to a queue and executed in order. We call all objects in this queue "colleagues". The communication between colleagues is coordinated through Timer, which plays the role of mediator.

Internet test center (ALI + Baidu + Tencent + byte beat + meituan + JD)

Posted by dardsemail on Thu, 25 Nov 2021 12:24:19 -0800