• Introduce the mediator pattern
  • Mediator pattern instance
  • Broker pattern analysis

Introduce the mediator pattern

You imagine there are ten people to finish a job, they are mutual cooperation and communication, and according to the other side of the notice is likely to change their state, but this often leads to many problems, the process is too complex, makes everyone should not only focus on their own things, but also to communicate with others, be notified, and need to juggle many state changes. At that time, we can consider the introduction of a similar perspective, the role of god is to introduce a broker, he responsible for receiving everyone’s notice, and will be needed to send a person to change, is to he to control and adjust the work schedule and details, the man often from overall consideration, so that each worker only need to consider their own problems, once the change, Just notify the arbitrator and let the arbitrator decide. So it turns out to be a whole team communication process, where the team members report to the mediator, and the mediator gives the team orders. This is also common in real life. Each department usually has a leader and each class has a monitor. The monitor is usually responsible for receiving the information from the students and then sending it to the students from the monitor, who acts as an arbiter and the students act as group members.

This is the basic idea of mediator mode. Mediators mean both mediator and mediator. On the one hand, they notify the mediator when something troublesome happens, and they also notify the mediator when something happens to the design team. When the arbiter gives instructions, the group immediately executes them. Instead of communicating with each other and making personal decisions, team members report to an arbiter on everything that happens. The arbiter, on the other hand, decides what the group members report from the perspective of the whole team.

An instance of the mediator pattern

We implement a simple arbitrator pattern through a GUI program

See above is a login box we often see. The login box is usually designed for many state changes, such as the following logic is implemented in this example

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

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

If you delete the username again, the password changes back to disabled

If you select tourist login, both are disabled.

Assuming we have such a requirement, how should we program it? The initial idea is that each control separately accepts the state of the related control and changes its own state according to the different state. This can be done, but if we add a new control at this time, the logic is scattered in the control code, so it is difficult to modify, and each control is bloated with state control code, so the control should focus on implementing its own logic. Because these controls are interrelated, mutually restricted, all coupled together. According to the principle of object-oriented design, we should try to achieve the state of loose-coupling by over-coupling objects.

So, we can use the mediator pattern, each control changes, we send the change to the mediator, the mediator to deal with it, so that the control only needs to focus on its own implementation.

First look at the class diagram:

First, define the Mediator interface

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

Copy the code

Defining the Colleague interface

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

Copy the code

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 setMethod () {// Save method (); } public voidsetColleagueEnabled(Boolean Enabled) {// Mediator instructs to enable/disable mediatorssetEnabled(enabled); }}Copy the code
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) {  // 构造函数 
        super(caption, group, state);
    }
    public void setMethod () {// Save method (); } public voidsetColleagueEnabled(Boolean Enabled) {// Mediator issues enable/disable instructionssetEnabled(enabled); } public void itemStateChanged (ItemEvent e) {/ / when the state change notification Mediator Mediator. ColleagueChanged (); }}Copy the code
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 super(text, columns); } public voidsetMethod () {// Save method (); } public voidsetColleagueEnabled(Boolean Enabled) {// Mediator instructs to enable/disable mediatorssetEnabled(enabled);
        setBackground(enabled ? Color.white : Color.lightGray); } public void textValueChanged (TextEvent e) {/ / when text change notification Mediator Mediator. ColleagueChanged (); }}Copy the code

Finally, a concrete intermediary object is implemented

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. // After creating and configuring each Colleague, the dialog box is displayed. public LoginFrame(String title) { super(title);setBackground(Color.lightGray); // Use layout manager to generate 4×2 panessetLayout(new GridLayout(4, 2)); Create Colleague createColleagues(); / / configure the add (checkGuest); add(checkLogin); add(new Label("Username:"));
        add(textUser);
        add(new Label("Password:")); add(textPass); add(buttonOk); add(buttonCancel); // Set the initial enable/disable state colleagueChanged(); / / show the pack (); show(); } // Generate colleagues. public voidcreateColleagues() {// 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(The '*');
        buttonOk = new ColleagueButton("OK");
        buttonCancel = new ColleagueButton("Cancel"); // setMediator checkguest.setMediator (this); checkLogin.setMediator(this); textUser.setMediator(this); textPass.setMediator(this); buttonOk.setMediator(this); buttonCancel.setMediator(this); / / set the Listener checkGuest. AddItemListener (checkGuest); checkLogin.addItemListener(checkLogin); textUser.addTextListener(textUser); textPass.addTextListener(textPass); buttonOk.addActionListener(this); buttonCancel.addActionListener(this); } // Receive notifications from Colleage and determine the enabled/disabled status of each Colleage. public voidcolleagueChanged() {
        if (checkGuest.getState()) { // Guest mode
            textUser.setColleagueEnabled(false);
            textPass.setColleagueEnabled(false);
            buttonOk.setColleagueEnabled(true);
        } else { // Login mode
            textUser.setColleagueEnabled(true); userpassChanged(); }} // Check whether colleages are enabled or disabled when textUser or textPass text input box text changesuserpassChanged() {
        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); }}Copy the code

The Main class

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

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

The results

Broker pattern analysis

The mediator pattern has several roles

  • The Mediator is the interface that defines the control logic, receives messages from members, and processes them, corresponding to the Mediator interface in the example
  • Specific intermediaries implement interfaces and make different logic according to different requirements
  • A Colleague is an interface for a group to define corresponding methods
  • Specific team members are responsible for implementing specific team logic and passing the notification directly to the intermediary for execution

Class diagram for the mediator pattern: