1. define

All related objects communicate through intermediary objects rather than referring to each other, so when an object changes, the intermediary object is notified. 2. The core

The netted many-to-many relationship becomes a relatively simple one-to-many relationship (the complex scheduling is handed over to the mediator)

  1. implementation

Multiple objects, not necessarily instantiated objects, can also be understood as independent items. While these items are being processed, they need to be known and processed with data from other items.

If each item was handled directly, the program would be very complex, and to change something would have to be changed within multiple items

We take this process out and encapsulate it as an intermediary. We can notify the intermediary when everything needs to be processed

var A = {
    score: 10.changeTo: function(score) {
        this.score = score;
        // get it yourself
        this.getRank();
    },
    // Get it directly
    getRank: function() {
        var scores = [this.score, B.score, C.score].sort(function(a, b) {
            return a < b;
        });
        console.log(scores.indexOf(this.score) + 1); }};var B = {
    score: 20.changeTo: function(score) {
        this.score = score;
        // Get it through an intermediaryrankMediator(B); }};var C = {
    score: 30.changeTo: function(score) {
        this.score = score; rankMediator(C); }};// The broker calculates the ranking
function rankMediator(person) {
    var scores = [A.score, B.score, C.score].sort(function(a, b) {
        return a < b;
    });
    console.log(scores.indexOf(person.score) + 1);
}
// A handles by itself
A.changeTo(100); / / 1
// B and C are handled by intermediaries
B.changeTo(200); / / 1
C.changeTo(50); / / 3
Copy the code

ABC three wanted to know their own ranking after their scores were changed, so THEY dealt with it by themselves in A, while B and C used an intermediary. B and C will be easier and the overall code will be cleaner

Finally, although mediators can decouple modules from objects, sometimes the relationship between objects does not have to be decoupled, and forcing an intermediary to integrate can make code more cumbersome and requires attention.