Mediator_javascript in javascript design patterns

Source: Internet
Author: User
This article mainly introduces the Mediator mode of the javascript design mode. For more information, see I. Overview

1. Introduction

In our daily life, for example, we go to a house agency to rent a house. a house intermediary forms an intermediary between the house rental agency and the landlord. The tenant does not care about the house he rents. The landlord also doesn't care who he rents. The existence of an intermediary makes the transaction so convenient.

In the process of software development, it is inevitable that multiple classes or subsystems interact with each other, and the interaction is cumbersome, as a result, each class must know the class that needs to be interacted with, so that their coupling will become abnormal. The consequences are very serious and the Big Bear is angry !~~~~ (>_< )~~~~

Now that the question has been raised, let's take the lead in this issue-intermediary mode.

The intermediary's function is to encapsulate interaction between objects. If the operation of an object causes changes to other related objects and the object does not want to handle these relationships by itself, you can find the intermediary, let it deal with these troublesome relationships. Let's look at the following small example:

The code is as follows:


Var Participant iPant = function (name ){
This. name = name;
This. chatroom = null;
};
Particle. prototype = {
Send: function (message, ){
This. chatroom. send (message, this, );
},
Receive: function (message, from ){
Log. add (from. name + "to" + this. name + ":" + message );
}
};
Var Chatroom = function (){
Var particle table = {};
Return {
Register: function (participant Ant ){
Maid [maid. name] = maid;
Participant. chatroom = this;
},
Send: function (message, from, ){
If (){
To. receive (message, from );
} Else {
For (key in Maid ){
If (maid [key]! = From ){
Maid [key]. receive (message, from );
}
}
}
}
};
};
Var log = (function (){
Var log = "";
Return {
Add: function (msg) {log + = msg + "\ n ";},
Show: function () {alert (log); log = "";}
}
})();
Function run (){
Var yoko = new maid ("Yoko ");
Var john = new maid ("John ");
Var paul = new maid ("Paul ");
Var ringo = new maid ("Ringo ");
Var chatroom = new Chatroom ();
Chatroom. register (yoko );
Chatroom. register (john );
Chatroom. register (paul );
Chatroom. register (ringo );
Yoko. send ("All you need is love .");
Yoko. send ("I love you John .");
John. send ("Hey, no need to broadcast", yoko );
Paul. send ("Ha, I heard that! ");
Ringo. send ("Paul, what do you think? ", Paul );
Log. show ();
}

In the sample code, we have four participants who join a chat session and register a chat room (intermediary ). Representatives of participants. The participants send messages to each other and process routes in the chat room.

The chat room objects play an intermediary role, coordinate other objects, organize them reasonably, and reduce coupling.

II. source code case reference

We should be familiar with MVC three-layer Model entity Model, View, and Control/Mediator ).

The control layer is the intermediary between the presentation layer and the model layer. In general, MVC is also an application of the intermediary model in the framework design.

III. case introduction

The code is as follows:


Function Player (name ){
This. points = 0;
This. name = name;
}
Player. prototype. play = function (){
This. points + = 1;
Mediator. played ();
};
Var scoreboard = {
Element: document. getElementById ('results '),
Update: function (score ){
Var I, msg = '';
For (I in score ){
If (score. hasOwnProperty (I )){
Msg + ='

'+ I +' <\/strong> :';
Msg + = score [I];
Msg + = '<\/p> ';
}
}
This. element. innerHTML = msg;
}
};
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;
If (e. which = 49 ){
Mediator. players. home. play ();
Return;
}
If (e. which = 48 ){
Mediator. players. guest. play ();
Return;
}
}
};
Mediator. setup ();
Window. onkeypress = mediator. keypress;
SetTimeout (function (){
Window. onkeypress = null;
Console. log ('game over! ');
},30000 );

IV. Summary

Why Mediator?

There are many interaction operations between objects. each object's behavior operations depend on each other. modifying the behavior of an object also involves modifying the behavior of many other objects,

If the Mediator mode is used, the coupling between objects can be loose. you only need to care about the relationship with the Mediator, and the multi-to-many relationship becomes a one-to-many relationship,

This reduces system complexity and improves scalability.

Use intermediary mode

1. a group of well-defined objects now require complex communication.

2. create a behavior that is distributed across multiple classes without generating too many child classes.

It can be seen that the intermediary object is mainly used to encapsulate behavior, and the participants of behavior are those objects, but through the intermediary, these objects do not need to know each other. (Implementation of the Dimit law)

Advantages of using the intermediary mode:

1. the coupling between system objects is reduced, making objects easy to be reused independently.

2. improve system flexibility and make the system easy to expand and maintain.

Disadvantages of using the intermediary mode:

The disadvantages of the intermediary mode are obvious, because this "intermediary" assumes a lot of responsibilities, so once this intermediary object encounters a problem, the entire system will be significantly affected.

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.