Mediator Pattern is also called Mediator Pattern or Mediator Pattern. By encapsulating a set of object interactions with a mediation object, the mediator makes the objects loosely coupled without explicitly interacting with each other, and can change their interactions independently.

The mediator pattern wraps up a set of ways in which objects interact so that they don’t have to obviously interact with each other. Changes in the roles of some objects do not immediately affect the roles of other objects. Ensure that these functions can vary independently of each other. The core idea is that the direct coupling of hierarchical objects is decoupled by the intermediary, and the external dependent communication of hierarchical objects is forwarded by the intermediary.

I. Application scenarios of intermediary mode

In real life, the existence of intermediaries is indispensable, if there is no intermediary, we can not communicate with friends from afar. Each object will reference each other, and if each object interacts with multiple objects, it will form a mesh structure as shown in the figure below.

As you can see from the above figure, there is excessive coupling between each object, which is not conducive to information reuse and extension. If the mediator pattern is introduced, the relationship between objects will become a star structure, as shown in the following figure after the mediator pattern is adopted:

After the introduction of the mediator pattern, the change of any class will only affect the mediator class itself. In the previous design, the change of any class will cause the change of all its associated classes. This design reduces the coupling degree of the system.

In fact, the wechat circle of friends we brush every day in our daily life is a mediator. There is also information trading platform, which is also the embodiment of the intermediary model.

The mediator pattern is used to reduce the complexity of communication between multiple objects and classes. By providing an intermediary class, the many-to-many relationship between objects at all levels of the system is changed into one-to-many relationship, and the intermediary object can change the complex network structure into the star structure with mediator as the center, so as to reduce the complexity of the system and improve the scalability.

If there are a lot of connection between system at all levels object relations, namely hierarchy is complicated reticular structure, if they are tightly coupled communication directly, cause the system structure is complicated, and one of the hierarchy changes, is tightly coupled with the corresponding hierarchy also need to modify, system is hard to maintain. By adding an intermediary level object to the system, all the behaviors of other levels that need external communication are forwarded by the intermediary, and the system presents a star structure with the intermediary as the center for communication, which greatly reduces the complexity of the system.

Simply put, if multiple classes are coupled to form a network structure, you need to consider using the intermediary pattern for optimization. The broker pattern applies to the following scenarios:

  • There are complex reference relations between objects in the system, and the interdependent relations generated are chaotic and difficult to understand.
  • The common behavior of the interaction, and a new mediator class can be added if the behavior needs to be changed.

The mediator pattern mainly consists of four roles:

  • Mediators: Define a unified interface for communication between the roles of the user’s colleagues;
  • Concreatemediators: Receive messages from concrete colleague objects and coordinate collaboration among colleague objects;
  • An abstract Colleague: Each Colleague object needs to rely on the role of a mediator to forward communication with other colleagues.
  • ConcreteColleague: Responsible for implementing self-methods and forwarding dependent methods to mediators for coordination.

1.1 The simple chat room system uses the intermediary mode

Suppose we want to build a chat room system where users can send messages to the chat room, and the chat room displays messages to all users. Actually is the user sends the message and the chat room display communication process, but the user cannot directly send the information to the chat room, but needs to send the information to the server first, and then the server will send the message to the chat room for display. The specific code is as follows.

Create 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 sendMsg(String msg) {
        chatRoom.showMsg(this, msg);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) { this.name = name; }}Copy the code

Create ChatRoom class:

public class ChatRoom {

    public void showMsg(User user, String msg) {
        System.out.println("[" + user.getName() + "]."+ msg); }}Copy the code

Test main method:

public static void main(String[] args) {

    ChatRoom chatRoom = new ChatRoom();

    User kevin = new User("Kevin", chatRoom);
    User jhon = new User("Jhon", chatRoom);
    kevin.sendMsg("Hello, Jhon!");
    jhon.sendMsg("Hi, Kevin!");
}
Copy the code

Running results:

Two, the intermediary model in the source code

The schedule() method is overloaded in the Timer class.

Click on any of these methods and find that all of them end up calling the private Sched () method.

 private void sched(TimerTask task, long time, long period) {
    if (time < 0)
        throw new IllegalArgumentException("Illegal execution time.");

    // Constrain value of period sufficiently to prevent numeric
    // overflow while still being effectively infinitely large.
    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(); }}Copy the code

All tasks are added to a queue and executed sequentially. Call all objects in this queue colleagues. Colleagues are coordinated through Timer, and Timer assumes the role of mediator.

The advantages and disadvantages of the intermediary model

advantages

  • Reducing inter-class dependencies, transforming many-to-many dependencies into one-to-many, and reducing inter-class coupling;
  • Each category does its job, according to Demeter’s law.

disadvantages

  • The mediator pattern transforms the direct interdependence of multiple objects into a dependency between the mediator and multiple peer classes. The more colleague classes there are, the more bloated the mediator becomes, complex and difficult to maintain.