Deep understanding of the JavaScript series (36): The intermediary model of design patterns in detail _ basic knowledge

Source: Internet
Author: User

Introduced

Mediator mode (mediator), which encapsulates a series of object interactions with a mediation object. Intermediaries do not need to refer explicitly to each other, so that they are loosely coupled and can independently alter their interactions.

Main content from: http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/

Body

In software development, an intermediary is a behavioral design pattern that communicates the different parts of the system by providing a unified interface. Generally, if a system has many sub modules that require direct communication, create a central control point for each module to interact through the central control point. The mediator pattern allows these modules to be decoupled without direct communication.

For example, the usual airport traffic control system, the tower is the intermediary, it controls the aircraft (sub-module) of the Take-off and landing, because all communication is from the aircraft to the tower to complete the report, rather than the aircraft before communicating with each other. The central control system is the key of the system, which is the intermediary role in software design.

Let's start with pseudocode to understand:

Copy Code code as follows:

The following code is pseudo code, please do not care too much about the code
The app namespace is the equivalent of acting as an intermediary.
var app = App | | {};

Ajax requests via the app broker
App.sendrequest = function (options) {
Return $.ajax ($.extend ({}, Options);
}

After requesting the URL, show view
App.populateview = function (URL, view) {
$.when (App.sendrequest ({url:url, method: ' Get '})
. then (function () {
Display content
});
}

Empty content
App.resetview = function (view) {
View.html (");
}

In JavaScript, intermediaries are very common, the equivalent of the observer mode of the message bus, but not as the observer in the form of calling Pub/sub, but through the intermediary of the unified management, let us on the basis of the observer to give an example:
Copy Code code as follows:

var mediator = (function () {
Subscribe to an event and provide an event to trigger a later callback function
var subscribe = function (channel, FN) {
if (!mediator.channels[channel]) mediator.channels[channel] = [];
Mediator.channels[channel].push ({context:this, callback:fn});
return this;
},

   //Broadcast events
    publish = function (channel) {
     & nbsp;  if (!mediator.channels[channel]) return false;
        var args = Array.prototype.slice.call (arguments, 1);
        for (var i = 0, L = mediator.channels[channel].length i < l i++) {
            var subscription = mediator.channels[channel][ I];
            subscription.callback.apply ( Subscription.context, args);
       }
        return this;
   };

return {
Channels: {},
Publish:publish,
Subscribe:subscribe,
Installto:function (obj) {
Obj.subscribe = subscribe;
Obj.publish = publish;
}
};

} ());


The calling code is relatively simple:
Copy Code code as follows:

(function (mediator) {

function Initialize () {

Default value
Mediator.name = "Dudu";

Subscribe to an event NameChange
The callback function shows the information before and after the modification
Mediator.subscribe (' NameChange ', function (ARG) {
Console.log (this.name);
THIS.name = arg;
Console.log (this.name);
});
}

function UpdateName () {
Broadcast trigger event, parameter is new data
Mediator.publish (' NameChange ', ' Tom '); Dudu, Tom.
}

Initialize (); Class
UpdateName (); Call

}) (mediator);


intermediaries and observers

Here, you may be confused, the intermediary and the observer looks similar, what is the difference? It's a bit similar, but let's look at the specific description:

Observer mode, a single object that does not encapsulate constraints, instead, the Observer observer and the concrete class subject together to maintain the constraint, communication is interacted through multiple observers and multiple concrete classes: Each specific class usually contains multiple observers, And sometimes an observer in a particular class is a specific class of another observer.

The mediator model does not simply distribute, but acts as a responsibility to maintain these constraints.

Intermediaries and appearance patterns

Many people may also be confused by the difference between the mediator and the appearance pattern, they are all the existing modules are abstracted, but there are some subtle differences.

What the mediator does is to communicate between modules, but the appearance pattern simply defines a simple interface for a module or system without adding additional functionality. The concept of other modules and appearance patterns in the system is not directly related, and can be considered one-way.


A complete example is given:

Copy Code code as follows:

<!doctype html>
<title>javascript patterns</title>
<meta charset= "Utf-8" >
<body>
<div id= "Results" ></div>
<script>
function Player (name) {
this.points = 0;
THIS.name = name;
}
Player.prototype.play = function () {
This.points + 1;
Mediator.played ();
};
var scoreboard = {

Container for displaying content
Element:document.getElementById (' Results '),

Update score Display
Update:function (Score) {
var i, msg = ';
For (i in score) {
if (Score.hasownproperty (i)) {
msg + + ' <p><strong> ' + i + ' <\/strong>: ';
msg + score[i];
msg + ' <\/p> ';
}
}
This.element.innerHTML = msg;
}
};

var mediator = {

All the player
Players: {},

           //initialization
             setup:function () {
                 var players = This.players;
                players.home = new Player (' home ');
                players.guest = New Player (' Guest ');
           },

           //play, update score
             played:function () {
                 var players = this.players,
                     score = {
                          Home:players.home.points,
                         Guest:players.guest.points
                    };

Scoreboard.update (score);
},

Handling User Key interaction
Keypress:function (e) {
E = e | | window.event; Ie
if (E.which = = 49) {//numeric Key "1"
Mediator.players.home.play ();
Return
}
if (E.which = = 48) {//numeric key "0"
Mediator.players.guest.play ();
Return
}
}
};

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

30 seconds to end.
settimeout (function () {
Window.onkeypress = null;
Console.log (' Game over! ');
}, 30000);
</script>
</body>

Summarize

The mediator pattern is generally applied to situations where a group of objects are well defined but communicate in a complex manner, in general, the intermediary mode is very easy to use in the system, but also easy to misuse in the system, when the system appears a Many-to-many interactive complex object group, do not rush to use the intermediary mode, But to think about whether there is a problem with the system design.

In addition, because the mediator pattern turns the interaction complexity into the mediator's own complexity, the mediator object is more complex than any other object.

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.