current position:Home>Mediator pattern of JavaScript Design Pattern

Mediator pattern of JavaScript Design Pattern

2021-08-27 14:23:10 Niu Niu_ lz

This is my participation 8 The fourth of the yuegengwen challenge 11 God , Check out the activity details :8 Yuegengwen challenge

The function of mediator model is to release the tight coupling between objects . After adding a mediator object , All related objects communicate through mediator objects , Instead of quoting each other , So when an object changes , Just notify the intermediary object .

A real intermediary

1 Airport Commander

Intermediaries are also called mediators . The reality is , Every plane only needs to communicate with the command tower . The command tower acts as a mediator , Know the flight status of every plane , So it can arrange the take-off and landing time of all aircraft , Make route adjustment in time .

2 bookmaker

Buy football lottery tickets during the World Cup , Gambling companies act as intermediaries , Everyone only needs to be associated with the gambling company , The gambling company will calculate the odds according to everyone's bets , When the lottery winners win, they take money from the gambling company , If you lose money, give it to the gambling company .

An example of the intermediary model —— Purchase goods

demand : Realize the page of buying mobile phones , In the purchase process , You can select the color of the phone and enter the purchase quantity , At the same time, there are two display areas in the page , Show the user the color and quantity just selected . There is also a button to dynamically display the next operation , We need to query the stock corresponding to the color mobile phone , If the stock quantity is less than the purchase quantity , The button will be disabled and will display out of stock , On the contrary, the button can be clicked and displayed in the shopping cart .

Assume that the mobile phone inventory is :

var goods = {
  "red": 3,
  "blue": 6
}
 Copy code 

Then in the page , There will be several scenarios :

  1. Select the red phone , Buy 4 individual , Insufficient inventory .
  2. Select blue phone , Buy 5 individual , There's plenty of stock , Can be added to the shopping cart .
  3. When the purchase quantity is not entered , The button will be disabled and the corresponding prompt will be displayed .

So basically at least 5 Nodes :

  • Drop down the selection box colorSelect
  • Text input box numberInput
  • Show color information colorInfo
  • Display purchase quantity information numberInfo
  • The button that determines the next operation nextBtn

Start coding

HTML Code :

 Choose a color :
<select id="colorSelect">
  <option value=""> Please select </option>
  <option value="red"> Red </option>
  <option value="blue"> Blue </option>
</select>
 Enter the purchase quantity : <input type="text" id="numberInput" />
 You have chosen a color : <div id="colorInfo"></div>
 You entered the quantity : <div id="numberInfo"></div>
<button id="nextBtn" disabled="true"> Please select the phone color and purchase quantity </button>
 Copy code 

Next, we will listen to colorSelect Of onchange Event functions and numberInput Of oninput Event function , Then deal with these two events accordingly .

var colorSelect = document.getElementById('colorSelect'),
  numberInput = document.getElementById('numberInput'),
  colorInfo = document.getElementById('colorInfo'),
  numberInfo = document.getElementById('numberInfo'),
  nextBtn = document.getElementById('nextBtn');

var goods = { //  Mobile phone inventory  
  "red": 3,
  "blue": 6
};
colorSelect.onchange = function () {
  var color = this.value, //  Color 
    number = numberInput.value,
    stock = goods[color]; //  The current stock corresponding to the mobile phone in this color 
  colorInfo.innerHTML = color;
  if (!color) {
    nextBtn.disabled = true;
    nextBtn.innerHTML = ' Please select the phone color ';
    return;
  }
  if (((number - 0) | 0) !== number - 0) {
    nextBtn.disabled = true;
    nextBtn.innerHTML = ' Please enter the correct purchase quantity ';
    return;
  }
  //  Whether the purchase quantity entered by the user is a positive integer 
  if (number > stock) { //  The currently selected quantity does not exceed the stock quantity  
    nextBtn.disabled = true;
    nextBtn.innerHTML = ' Insufficient inventory ';
    return;
  }
  nextBtn.disabled = false;
  nextBtn.innerHTML = ' Put it in the shopping cart ';
};
 Copy code 

The connection between objects

Think about it , When triggered colorSelect Of onchange after , What will happen . First of all, we have to let colorInfo Displays the currently selected color , Then get the purchase quantity currently entered by the user , Make some legitimacy judgment on the user's input value . Then judge according to the inventory quantity nextBtn Display status of .

numberInput.oninput = function () {
  var color = colorSelect.value, //  Color 
    number = this.value, //  Number 
    stock = goods[color]; //  The current stock corresponding to the mobile phone in this color 
  numberInfo.innerHTML = number;
  if (!color) {
    nextBtn.disabled = true;
    nextBtn.innerHTML = ' Please select the phone color ';
    return;
  }
  if (((number - 0) | 0) !== number - 0) {
    nextBtn.disabled = true;
    nextBtn.innerHTML = ' Please enter the correct purchase quantity ';
    return;
  }
  if (number > stock) { //  The currently selected quantity does not exceed the stock quantity  
    nextBtn.disabled = true;
    nextBtn.innerHTML = ' Insufficient inventory ';
    return;
  }
  nextBtn.disabled = false;
  nextBtn.innerHTML = ' Put it in the shopping cart ';
};
 Copy code 

Possible difficulties

Although the coding has been successfully completed so far , But the consequent demand change may bring us trouble . Suppose you now ask to remove colorInfo and numberInfo These two display areas , We have to change it separately colorSelect.onchange and numberInput.onput Code inside , Because in the previous code , These objects are indeed coupled together .

So now , We need to add another drop-down selection box in the page , Represents the selection of mobile phone memory , We need to calculate the color 、 Memory and purchase quantity nextBtn Whether to show insufficient inventory or put it in the shopping cart .

First, add two HTML node :

 Choose memory :
<select id="memorySelect">
  <option value=""> Please select </option>
  <option value="32G">32G</option>
  <option value="16G">16G</option>
</select>
 You have selected memory : <div id="memoryInfo"></div>
<script> memorySelect = document.getElementById('memorySelect'), memoryInfo = document.getElementById('memoryInfo') </script>
 Copy code 

Next, modify the that represents the repository JSON Objects and modifications colorSelect Of onchange Event function :

var goods = { //  Mobile phone inventory 
  "red|32G": 3, //  Red  32G, The inventory quantity is  3 
  "red|16G": 0,
  "blue|32G": 1,
  "blue|16G": 6
};
colorSelect.onchange = function () {
///  In addition to the above code , There are the following judgments 
  var color = this.value, //  Color 
    number = numberInput.value,
    stock = goods[color + '|' + memory]; //  The current stock corresponding to the mobile phone in this color 

  if (!memory) {
    nextBtn.disabled = true;
    nextBtn.innerHTML = ' Please select memory size ';
    return;
  }
}
 Copy code 

Also change some numberInput Event related code .

Finally, add memorySelect Of onchange Event function :

memorySelect.onchange = function () {
  var color = colorSelect.value,
    number = numberInput.value,
    memory = this.value,
    stock = goods[color + '|' + memory];
  if (!color) {
    nextBtn.disabled = true;
    nextBtn.innerHTML = ' Please select the phone color ';
    return;
  }
  if (!memory) {
    nextBtn.disabled = true;
    nextBtn.innerHTML = ' Please select memory size ';
    return;
  }
  if (((number - 0) | 0) !== number - 0) {
    nextBtn.disabled = true;
    nextBtn.innerHTML = ' Please enter the correct purchase quantity ';
    return;
  }
  if (number > stock) { //  The currently selected quantity does not exceed the stock quantity 
    nextBtn.disabled = true;
    nextBtn.innerHTML = ' Insufficient inventory ';
    return;
  }
  nextBtn.disabled = false;
  nextBtn.innerHTML = ' Put it in the shopping cart ';
}
 Copy code 

We can see , Only one memory selection condition is added , You need to modify so much code , This is because in the current implementation , Each node object is coupled together , Change or add any node object , Should be notified to its related objects .

Introducing intermediaries

Now introduce the mediator object , All node objects communicate only with mediators . When the drop-down selection box colorSelectmemorySelect And text input boxes numberInput When an event occurs , They just inform the mediator that they have been changed , At the same time, it passes itself as a parameter to the mediator , So that the mediator can identify who has changed . Everything else is left to the mediator object .

var goods = { //  Mobile phone inventory  
  "red|32G": 3,
  "red|16G": 0,
  "blue|32G": 1,
  "blue|16G": 6
};
var mediator = (function () {
  var colorSelect = document.getElementById('colorSelect'),
    memorySelect = document.getElementById('memorySelect'),
    numberInput = document.getElementById('numberInput'),
    colorInfo = document.getElementById('colorInfo'),
    memoryInfo = document.getElementById('memoryInfo'),
    numberInfo = document.getElementById('numberInfo'),
    nextBtn = document.getElementById('nextBtn');
  return {
    changed: function (obj) {
      var color = colorSelect.value, //  Color  
        memory = memorySelect.value,//  Memory  
        number = numberInput.value, //  Number  
        stock = goods[color + '|' + memory];  //  Number of phones in stock corresponding to color and memory 
      if (obj === colorSelect) { //  If the change is to select the color drop-down box  
        colorInfo.innerHTML = color;
      } else if (obj === memorySelect) {
        memoryInfo.innerHTML = memory;
      } else if (obj === numberInput) {
        numberInfo.innerHTML = number;
      }
      if (!color) {
        nextBtn.disabled = true;
        nextBtn.innerHTML = ' Please select the phone color ';
        return;
      }
      if (!memory) {
        nextBtn.disabled = true;
        nextBtn.innerHTML = ' Please select memory size ';
        return;
      }
      if (((number - 0) | 0) !== number - 0) {
        nextBtn.disabled = true;
        nextBtn.innerHTML = ' Please enter the correct purchase quantity ';
        return;
      }
      nextBtn.disabled = false;
      nextBtn.innerHTML = ' Put it in the shopping cart ';
    }
  }
})();
//  Event function :
colorSelect.onchange = function () {
  mediator.changed(this);
};
memorySelect.onchange = function () {
  mediator.changed(this);
};
numberInput.oninput = function () {
  mediator.changed(this);
};
 Copy code 

As you can imagine , One day we will add some nodes related to requirements , such as CPU model , Then we just need to change it a little mediator Object can :

var goods = { //  Mobile phone inventory 
  "red|32G|800": 3, //  Color  red, Memory  32G,cpu800, The corresponding inventory quantity is  3
  "red|16G|801": 0,
  "blue|32G|800": 1,
  "blue|16G|801": 6
};
var mediator = (function () {
  var cpuSelect = document.getElementById('cpuSelect');
  return {
    change: function (obj) {
      //  A little 
      var cpu = cpuSelect.value,
        stock = goods[color + '|' + memory + '|' + cpu];
    }
  }
  //  A little 
  if (obj === cpuSelect) {
    cpuInfo.innerHTML = cpu;
  }
})();
 Copy code 

The advantages and disadvantages of the mediator model

Intermediary model Decouple objects , The net many to many relationship between objects is replaced by the one to many relationship between mediators and objects . Each object only needs to pay attention to the implementation of its own function , The interaction between objects is left to the mediator object to implement and maintain .

however , The mediator model also has some disadvantages . among , The biggest drawback is A mediator object will be added to the system , Because of the complexity of the interaction between objects , The complexity of transitioning to an intermediary object , Make the intermediary object often huge . The mediator object itself is often a difficult object to maintain .

And finally

If this article is helpful to you , Or if there's some inspiration , Give me some praise and pay attention to , Your support is my biggest motivation for writing , Thank you for your support .

copyright notice
author[Niu Niu_ lz],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210827142304339q.html

Random recommended