Design Patterns of the Mediator Pattern (mediator pattern) Introducing the mediator pattern Examples of the mediator pattern Analysis of the mediator pattern


  • Introduction of the intermediary model
  • Intermediary pattern example
  • Analysis of the intermediary model

Introduction of the intermediary model

One imagines there are ten people who have to work together on a job, they have to cooperate and communicate with each other and may have to change their status depending on each other's notifications, but this usually causes a lot of problems with overly complex processes that make each person not only focus on their own thing, but also communicate with others, get notifications and need to juggle a lot of status changes. At this point, we consider that we can introduce a role similar to God's perspective, that is, introduce an intermediary who will be responsible for receiving notifications from each person and sending the changes to the required person, that is, to control and regulate the progress and details of the work, this person tends to think in terms of the whole, so making each individual worker only need to think about their own problems, and once there is a change, notify the arbiter and leave it to the arbiter to decide. So it ends up being, the whole team communication process, with the group reporting to the intermediary and the intermediary giving only orders to the group. This is also common in real life, where each department usually has a leader and each class has a class president, who is often responsible for receiving information from classmates and then sending the above information from the class president to the classmates, where the class president is the equivalent of an arbiter and the classmates are the equivalent of group members.

This is the basic idea of the mediator pattern, mediator has the meaning of arbiter and mediator, on the one hand, notifying the arbiter when troublesome things happen and also notifying the arbiter when things happen that are designed for the whole group. When the arbiter gives instructions, the group will immediately carry them out. Instead of team members communicating with each other and making private decisions, anything that happens is reported like an arbiter. On the other hand, the arbiter makes decisions on things reported by group members in the context of the whole team.

Example of the Intermediary pattern

We implement a simple arbiter pattern with a gui program

image.png

Look at the image above for a login box that we often see. Usually the login box is designed with a lot of state changes, for example, we have to implement the following logic for this example

First, if you select User Login, then the username input box is enabled, but the password input box is disabled, as shown below

image.png

If the user enters a username, the password box is enabled, as follows

image.png

If the username is deleted again, then the password becomes disabled again

image.png

If you select the visitor login, they are all disabled.

image.png

Assuming we have such a need, how should we write the program? The first idea was that each control would accept the state of the related control separately, and change its own state depending on the different states. This is functional, but suppose at this point we add a new control in, then since this logic is scattered throughout the individual control's code, we have a lot of trouble modifying it, and each control is filled with state control code that is bloated and the control should focus on implementing its own logic. Because these controls are all interrelated and inter-constrained, all coupled together. According to object-oriented design principles, we should try to overcouple objects and achieve a loosely coupled state.

So, we can use the intermediary pattern, where each control changes, we send the changes to the intermediary, and the intermediary handles them uniformly, so that the control just needs to focus on its own implementation.

First look at the class diagram.

image.png

First, define the Mediator interface

public interface Mediator {
    public abstract void createColleagues();
    public abstract void colleagueChanged();
}

Defining the Colleague Interface

public interface Colleague {
    public abstract void setMediator(Mediator mediator);
    public abstract void setColleagueEnabled(boolean enabled);
}

Implement three colleague classes.

import java.awt.Button;

public class ColleagueButton extends Button implements Colleague {
    private Mediator mediator;
    public ColleagueButton(String caption) {
        super(caption);
    }
    public void setMediator(Mediator mediator) {            //  saveMediator
        this.mediator = mediator;
    }
    public void setColleagueEnabled(boolean enabled) {      // Mediator commission/ Instructions for disabling 
        setEnabled(enabled);
    }
}
import java.awt.Checkbox;
import java.awt.CheckboxGroup;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;

public class ColleagueCheckbox extends Checkbox implements ItemListener, Colleague {
    private Mediator mediator;
    public ColleagueCheckbox(String caption, CheckboxGroup group, boolean state) {  //  constructor (computing) 
        super(caption, group, state);
    }
    public void setMediator(Mediator mediator) {            //  saveMediator
        this.mediator = mediator;
    }
    public void setColleagueEnabled(boolean enabled) {      // Mediator commission/ Disablement instructions
        setEnabled(enabled);
    }
    public void itemStateChanged(ItemEvent e) {             //  Notify when status changesMediator
        mediator.colleagueChanged();
    }
}
import java.awt.TextField;
import java.awt.Color;
import java.awt.event.TextListener;
import java.awt.event.TextEvent;

public class ColleagueTextField extends TextField implements TextListener, Colleague {
    private Mediator mediator;
    public ColleagueTextField(String text, int columns) {   //  constructor (computing)
        super(text, columns);
    }
    public void setMediator(Mediator mediator) {            //  saveMediator
        this.mediator = mediator;
    }
    public void setColleagueEnabled(boolean enabled) {      // Mediator commission/ Instructions for disabling
        setEnabled(enabled);
        setBackground(enabled ? Color.white : Color.lightGray);
    }
    public void textValueChanged(TextEvent e) {             //  Notify when text changesMediator
        mediator.colleagueChanged();
    }
}

Final implementation of the specific intermediary object

import java.awt.Frame;
import java.awt.Label;
import java.awt.Color;
import java.awt.CheckboxGroup;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class LoginFrame extends Frame implements ActionListener, Mediator {
    private ColleagueCheckbox checkGuest;
    private ColleagueCheckbox checkLogin;
    private ColleagueTextField textUser;
    private ColleagueTextField textPass;
    private ColleagueButton buttonOk;
    private ColleagueButton buttonCancel;

    //  constructor (computing)。
    //  Generate and configure eachColleague back, Show dialog box。
    public LoginFrame(String title) {
        super(title);
        setBackground(Color.lightGray);
        //  Using the Layout Manager to generate4×2 pane
        setLayout(new GridLayout(4, 2));
        //  Generate individualColleague
        createColleagues();
        //  configure
        add(checkGuest);
        add(checkLogin);
        add(new Label("Username:"));
        add(textUser);
        add(new Label("Password:"));
        add(textPass);
        add(buttonOk);
        add(buttonCancel);
        //  Set the initial enable start/ Disable status
        colleagueChanged();
        //  shows
        pack();
        show();
    }

    //  Generate individualColleague。
    public void createColleagues() {
        //  generate
        CheckboxGroup g = new CheckboxGroup();
        checkGuest = new ColleagueCheckbox("Guest", g, true);
        checkLogin = new ColleagueCheckbox("Login", g, false);
        textUser = new ColleagueTextField("", 10);
        textPass = new ColleagueTextField("", 10);
        textPass.setEchoChar('*');
        buttonOk = new ColleagueButton("OK");
        buttonCancel = new ColleagueButton("Cancel");
        //  set upMediator
        checkGuest.setMediator(this);
        checkLogin.setMediator(this);
        textUser.setMediator(this);
        textPass.setMediator(this);
        buttonOk.setMediator(this);
        buttonCancel.setMediator(this);
        //  set upListener
        checkGuest.addItemListener(checkGuest);
        checkLogin.addItemListener(checkLogin);
        textUser.addTextListener(textUser);
        textPass.addTextListener(textPass);
        buttonOk.addActionListener(this);
        buttonCancel.addActionListener(this);
    }

    //  Receive information fromColleage The notice then determines that eachColleage commissioning/ Disable status。
    public void colleagueChanged() {
        if (checkGuest.getState()) { // Guest mode
            textUser.setColleagueEnabled(false);
            textPass.setColleagueEnabled(false);
            buttonOk.setColleagueEnabled(true);
        } else { // Login mode
            textUser.setColleagueEnabled(true);
            userpassChanged();
        }
    }
    //  propertextUser either one or the othertextPass When the text in the text input box changes
    //  determineColleage commissioning/ Disable status
    private void userpassChanged() {
        if (textUser.getText().length() > 0) {
            textPass.setColleagueEnabled(true);
            if (textPass.getText().length() > 0) {
                buttonOk.setColleagueEnabled(true);
            } else {
                buttonOk.setColleagueEnabled(false);
            }
        } else {
            textPass.setColleagueEnabled(false);
            buttonOk.setColleagueEnabled(false);
        }
    }
    public void actionPerformed(ActionEvent e) {
        System.out.println(e.toString());
        System.exit(0);
    }
}

Main class

import java.awt.*;
import java.awt.event.*;

public class Main {
    static public void main(String args[]) {
        new LoginFrame("Mediator Sample");
    }
}

running result

image.png

Analysis of the intermediary model

The intermediary model has several main roles

  • intermediary is the interface responsible for defining the control logic that accepts messages from group members and processes them, corresponding to the Mediator interface in the example
  • Specific intermediaries Implement the interface and make different logic depending on the requirements
  • Colleague of Co-workers interface for group members, defining the appropriate methods
  • Specific group members Responsible for implementing specific group logic and directing notifications to intermediaries for execution

Class diagram of the intermediary model.

image.png


Recommended>>
1、A weekly technical article
2、Developments and Reflections on Big Data Cloud Computing and Artificial Intelligence
3、The most beautiful entrepreneur 21st public safety big data helmsman Liu Hongyan do not forget the original intention to forge ahead
4、New opportunities for autonomous driving development
5、A comprehensive discussion of the Data Centre Full Lifecycle Plus

    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号