Home > Article > Web Front-end > Detailed examples of the differences between Facade mode and Mediator mode in JavaScript design
Facade mode plays an important role in the architecture of this article. This mode is reflected in many JavaScript libraries or frameworks. The biggest role is to include High level APIs to hide the specific implementation. This means that we only expose the interface, and we can make the internal implementation ourselves. This also means that the internal implementation code can be easily modified and updated. For example, if you use jQuery to implement it today, and you want to change to YUI tomorrow, then It's very convenient.
In the following example, you can see that we provide a lot of private methods, and then expose a simple API to allow the outside world to execute and call internal methods:
var module = (function () { var _private = { i: 5, get: function () { console.log('current value:' + this.i); }, set: function (val) { this.i = val; }, run: function () { console.log('running'); }, jump: function () { console.log('jumping'); } }; return { facade: function (args) { _private.set(args.val); _private.get(); if (args.run) { _private.run(); } } } } ()); module.facade({run:true, val:10}); //outputs current value: 10, running
The difference between Facade and the mediator we are talking about below is that facade only provides existing functions, while mediator can add new functions.
Mediator Mode
Before talking about mediator, let’s give an example. The airport flight control system, which is the legendary tower, has absolute rights. He can Control the takeoff and landing time and place of any aircraft, and aircraft and aircraft were not allowed to communicate before. In other words, the tower is the core of the airport, and the mediator is equivalent to this tower.
Mediator is used when there are multiple modules in the program, and you don’t want each module to have dependencies, then the purpose of centralized control can be achieved through the mediator mode. Also in actual scenarios, mediator encapsulates many modules that you don't want to do, allowing them to be connected through the mediator, and at the same time loosely coupling them, so that they must communicate through the mediator.
What are the advantages of the mediator mode? That is decoupling. If you have a good understanding of the observer pattern before, it is relatively simple to understand the following mediator diagram. The following picture is a high level mediator pattern diagram:
Think about it, each module is a publisher, and the mediator is both a publisher and a subscriber.
Module 1 broadcasts a fact to Mediator, saying that something needs to be done
After Mediator captures the message, it immediately starts Module 2 that needs to be used to process the message. After Module 2 completes processing, it returns the information to Mediator
At the same time, Mediator also starts Module 3. When it accepts the message returned by Module 2, it automatically records the log to Module 3.
As you can see, there is no communication between the modules. In addition, Mediator can also implement monitoring. The function of each module status, for example, if Module 3 has an error, Mediator can temporarily only think of other modules, then restart Module 3, and then continue execution.
Looking back, we can see that the advantage of Mediator is that loosely coupled modules are controlled by the same Mediator. The modules only need to broadcast and listen for events, and there is no need for direct contact between modules. In addition, , multiple modules can be used for information processing at one time, and it is also convenient for us to uniformly add new modules to the existing control logic in the future.
Definitely: Since all modules cannot communicate directly, relatively speaking, there may be a slight decrease in performance, but I think it is worth it.
Let’s make a simple Demo based on the above explanation:
var mediator = (function(){ var subscribe = function(channel, fn){ if (!mediator.channels[channel]) mediator.channels[channel] = []; mediator.channels[channel].push({ context: this, callback: fn }); return this; }, publish = function(channel){ 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; } }; }());
Then there are 2 modules that are called separately:
//Pub/sub on a centralized mediator mediator.name = "tim"; mediator.subscribe('nameChange', function(arg){ console.log(this.name); this.name = arg; console.log(this.name); }); mediator.publish('nameChange', 'david'); //tim, david //Pub/sub via third party mediator var obj = { name: 'sam' }; mediator.installTo(obj); obj.subscribe('nameChange', function(arg){ console.log(this.name); this.name = arg; console.log(this.name); }); obj.publish('nameChange', 'john'); //sam, john
Application Facade: Abstraction of the core of the application
A facade works as an abstraction of the core of the application, between the mediator and Modules are responsible for communication, and each module can only communicate with the program core through this facade. As an abstraction, the responsibility is to ensure that a consistent interface (consistent interface) can be provided for these modules at all times, similar to the role of the sendbox controller. All module components communicate with the mediator through it, so the facade needs to be reliable and trustworthy. At the same time, as a function of providing an interface for the module, the facade also needs to play another role, that is, security control, which is to decide which part of the program Can be accessed by a module. Module components can only call their own methods and cannot access any unauthorized content. For example, a module may broadcast dataValidationCompletedWriteToDB, and the security check here needs to ensure that the module has write permission to the database.
In short, mediator can only process information after facade authorization detection.
Application Mediator: The core of the application
Mediator works as the core role of the application. Let’s briefly talk about his responsibilities. The core job is to manage the life cycle of the module. When this core captures any information coming in, it needs to determine how the program should handle it - that is, decide which module or modules to start or stop. When a module starts, it should be able to execute automatically without the application core deciding whether it should be executed (for example, whether it should be executed when the DOM is ready), so the module itself needs to make a decision.
You may still have questions, that is, under what circumstances will a module stop. When the program detects that a module has failed or an error has occurred, the program needs to make a decision to prevent the method in the module from continuing to be executed so that the component can be restarted. The main purpose is to improve the user experience.
In addition, the core should be able to dynamically add or delete modules without affecting any other functions. A common example is that a module is not available at the beginning of page loading, but after user operation, the module needs to be dynamically loaded and executed, just like the chat function in Gmail. From the perspective of performance optimization, it should be very good. Understand it.
Exception error handling is also handled by the application core. In addition, when each module broadcasts information, it also broadcasts any errors to the core so that the program core can stop/restart these modules according to the situation. This is also an important part of the loosely coupled architecture. We do not need to manually change any modules. We can do this by using publish/subscribe through the mediator.
The above is the detailed content of Detailed examples of the differences between Facade mode and Mediator mode in JavaScript design. For more information, please follow other related articles on the PHP Chinese website!