In-depth understanding of the JavaScript series (36): The mediator pattern of design patterns

Source: Internet
Author: User

introduces the mediator pattern (mediator), which encapsulates a series of object interactions with a mediation object. The mediator makes the objects not need to explicitly reference each other, so that they are loosely coupled, and can independently change the interaction between them. The main content is from: http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/#mediatorpatternjavascriptin the development of body software, the intermediary is a behavior design pattern, which provides a unified interface to communicate the different parts of the system. Generally, if the system has many sub-modules that require direct communication, create a central control point to allow its modules to interact with the central control point. The mediator mode allows these submodules to be decoupled without the need for direct communication. For example, the usual airport traffic control system, the tower is the intermediary, it controls the aircraft (sub-module) take-off and landing, because all the communication is from the aircraft to the Tower report to complete, rather than the aircraft before the communication with each other. Central control system is the key of the system, which is the role of intermediary in software design. Let's start with pseudo-code to understand://The following code is pseudo-code, please do not care too much about the code//The app namespace is the role of a mediatorvarApp = App | | {}; //Ajax requests through an app brokerApp.sendrequest =function(options) {return$.ajax ($.extend ({}, options);}//after requesting the URL, show viewApp.populateview =function(URL, view) {$.when (App.sendrequest ({url:url, method:' GET '}). Then (function(){         //Show Content     });} //Clear ContentApp.resetview =function(view) {view.html (‘‘);} In JavaScript, intermediaries are very common, equivalent to the message bus on the observer pattern, but not by calling pub like The Observer/sub form to achieve, but through the unification of intermediaries to manage, let us on the basis of the observer to give an example:varMediator = (function () {    //subscribe to an event and provide an event-triggered callback function    varSubscribe =function(channel, FN) {if(!mediator.channels[channel]) Mediator.channels[channel] = []; Mediator.channels[channel].push ({context: This, CALLBACK:FN}); return  This; },    //Broadcast EventsPublish =function(channel) {if(!mediator.channels[channel])return false; varargs = Array.prototype.slice.call (arguments, 1);  for(vari = 0, L = mediator.channels[channel].length; I < L; i++) {            varSubscription =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: (function(mediator) {functionInitialize () {//Default ValueMediator.name = "Dudu"; //Subscribe to an event NameChange        //callback function displays the information before and after the modificationMediator.subscribe (' NameChange ',function(ARG) {Console.log ( This. Name);  This. Name =Arg; Console.log ( This. Name);    }); }    functionUpdateName () {//broadcast trigger event, parameter is new dataMediator.publish (' NameChange ', ' Tom ');//Dudu, Tom.} initialize (); //InitializeUpdateName ();//called}) (mediator); When intermediaries and observers come here, you may be confused, what is the difference between intermediaries and observers? It's a bit similar, but let's take a look at the specific description: The Observer pattern, a single object without encapsulation constraints, instead, the Observer observer and the concrete class subject are together to maintain the constraints, Communication is done by interacting with multiple observers and specific classes: each specific class usually contains multiple observers, and sometimes one observer in a specific class is also a specific class of another observer. The intermediary model does not simply distribute, but acts as a duty to maintain these constraints. Intermediaries and appearance patterns many people may also be confused about the differences between intermediaries and appearance patterns, and they all abstract existing modules, but there are some subtle differences. What intermediaries do is to communicate between modules, which is multi-directional, 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 as unidirectional. The complete example gives a complete example:<!doctype html>functionPlayer (name) { This. Points = 0;  This. Name =name; } Player.prototype.play=function () {             This. Points + = 1;        Mediator.played ();        }; varScoreboard = {            //container for displaying contentElement:document.getElementById (' Results '),            //Update score DisplayUpdatefunction(score) {varI, msg = ' ';  for(Iinchscore) {                    if(Score.hasownproperty (i)) {msg+ = ' <p><strong> ' + i + ' <\/strong>: '; Msg+=Score[i]; Msg+ = ' <\/p> '; }                }                 This. element.innerhtml =msg;        }        }; varMediator = {            //all the playerplayers: {},//InitializeSetupfunction () {                varPlayers = This. Players; Players.home=NewPlayer (' Home '); Players.guest=NewPlayer (' Guest '); },            //after play, update your scorePlayed:function () {                varPlayers = This. Players, score={Home:players.home.points, Guest:players.guest.points                };            Scoreboard.update (score); },            //handling user Key InteractionsKeyPressfunction(e) {e= e | | window.event;//IE                if(E.which = = 49) {//number Key "1"Mediator.players.home.play (); return; }                if(E.which = = 48) {//number Key "0"Mediator.players.guest.play (); return;        }            }        }; //go!Mediator.setup (); Window.onkeypress=mediator.keypress; //end in 30 seconds .SetTimeout (function() {window.onkeypress=NULL; Console.log (' Game over! '); }, 30000); </script></body>Summary broker mode is generally applied to a set of objects are well-defined but in a complex way to communicate in the situation, generally, the intermediary mode is easy to use in the system, but also easy to misuse in the system, when the system appeared many pairs of multi-interactive complex object group, first 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 makes the interaction complexity the mediator's own complexity, it is said that the mediator object is more complex than any other object. Synchronization and recommendation this article has been synchronized to the directory index: in-depth understanding of JavaScript series in-depth understanding of the JavaScript series, including the original, translation, reprint and other types of articles, if it is useful to you, please recommend supporting a, to the power of the uncle writing. 

In-depth understanding of the JavaScript series (36): The mediator pattern of design patterns

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.