Easily master JavaScript Mediator pattern _javascript Skills

Source: Internet
Author: User

The role of mediator mode is to release the tightly coupled relationship between object and object, which is also called ' mediator '. All objects are communicated through the Mediator object, not by reference to each other, so when an object changes, only the mediator needs to be notified.

Such as: The Tower of the airport, each aircraft only need to communicate with the conning tower, the conning tower knows the flight status of each aircraft, can arrange all take-off and landing time, adjust the route and so on

The mediator pattern conforms to the Dimitri rule, the least-knowledge principle, where one object should know as little as possible about another object. If the coupling between objects is too high, then change an object, will affect many objects, difficult to maintain. When objects are tightly coupled, it is difficult to modify an object without affecting other objects.

If the complex coupling between objects does cause difficulty in invocation and maintenance, and the coupling increases exponentially as the project changes, then we can consider refactoring the code with the mediator pattern! The mediator promotes the maintainability of the code by decoupling.

Example 1: Game
Player objects are created through the player () constructor, with their own points and name attributes. The play () method on the prototype is responsible for adding a point to yourself and then notifying the intermediary:

 function Player (name) {
  this.points = 0;
  this.name = name;
Player.prototype.play = function () {
  this.points = 1;
  Mediator.played ();
}; 

The scoreboard object (scoreboard) has an update () method that is invoked by the broker each time the player is finished. The analysis does not know the player's information at all, and does not save the score, it is only responsible for showing the intermediary to the score:

 var scoreboard = {
  element:document.getElementById (' results '),
  update:function (score) {
    var i, msg = '; 
   for (i in score) {
      if (Score.hasownproperty (i)) {
        msg + + ' <p><strong> ' + i + ' <\/strong>: '; C7/>msg + = Score[i];
        msg + + ' <\/p> ';
      }
    }
    This.element.innerHTML = msg;
  }
; 

Now let's take a look at the Mediator object (the mediator). When the game is initialized, create the player in the Setup () method and then place the players property for subsequent use. The played () method is invoked by the player after each round, updating the score Hashijan table and passing it to scoreboard for display. The final method is KeyPress (), which is responsible for handling keyboard events, deciding which player to play with and informing it:

 var mediator = {
  players: {},
  setup:function () {
    var players = This.players;
    Players.home = new Player (' home ');
    Players.guest = new Player (' guest ');
  },
  played:function () {
    var players = this.players,
    score = {
      Home:players.home.points,
      Guest:players.guest.points
    };
    Scoreboard.update (score);
  },
  keypress:function (e) {
    e = e | | window.event;//IE
    if (E.which = 49) {//Key "1"
      mediator.players.home.play ();
      return;
    }
    if (E.which = =) {//Key "0"
      mediator.players.guest.play ();
      return;
    }
  }
; 

The last thing to do is initialize and end the game:

 Go!
Mediator.setup ();
window.onkeypress = mediator.keypress;

Game over in seconds
settimeout (function () {
  window.onkeypress = null;
  Alert (' Game over! ');
}, 30000); 

Example 2: Selling mobile phones

 var goods = {//Inventory ' red|32g ': 3, ' red|16g ': 5, ' blue|32g ': 3, ' blue|16g ': 6}//mediator var mediator = (function () {f
  Unction ID (ID) {return document.getElementById (ID); var colorselect = ID (' colorselect '), Memoryselect = ID (' memoryselect '), Numberinput = ID (' numberinput '), C Olorinfo = ID (' colorinfo '), Memoryinfo = ID (' memoryinfo '), Numberinfo = ID (' numberinfo '), nextbtn = ID (' NEXTBT
  n '); return{changed:function (obj) {var color = colorselect.value, memory = Memoryselect.value, Numbe r = numberinput.value, stock = goods[color+ ' | '
      +memory];
      if (obj = = colorselect) {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 choose the color of mobile phone ';
      Return } if (!memory) {Nextbtn.disabLED = true;
        nextbtn.innerhtml = ' Please choose memory size ';
      Return
        } if (Number.isinteger (number-0) && number > 0) {nextbtn.disabled = true;
        nextbtn.innerhtml = ' Please enter the correct purchase quantity ';
      Return
      } nextbtn.disabled = false;
    nextbtn.innerhtml = ' Put into shopping cart ';
}
  }
})(); Add Event Colorselect.onchange = function () {mediator.changed (this);} Memoryselect.onchange = function () {Mediator.chang
Ed (this); 

 } Numberinput.onchange = function () {mediator.changed (this);}

References: JavaScript mode "JavaScript design pattern and development practice"

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.