“This is the 18th day of my participation in the August Gwen Challenge.

preface

At the advanced end of the interview, there are often some questions about design patterns, and the answers are not good. Coincides with the activities of more challenges in August, I plan to spend a month to clarify the knowledge points about design patterns, to increase the confidence of my interview.

role

Programs are made up of single objects, large and small, all of which communicate according to certain relationships and rules. At the beginning of the program, an object may communicate with only a few objects. But as the program grows in size, there are more and more objects, and the communication between them becomes more and more complex, inevitably forming a network of many-to-many relationships. Mesh many-to-many relationships lead to tightly coupled objects, and programs become bloated and hard to maintain.

The role of the mediator pattern is to decouple objects from each other. By adding a mediator object, all related objects communicate through the mediator object rather than referring to each other, so when an object changes, the mediator object only needs to be notified. The mediator loosens the coupling between objects and can change their interactions independently. The mediator pattern turns the netted many-to-many relationship into a relatively simple one-to-many relationship.

Let me give you an example

A control tower for airport is one of the essential existence, if do not have a control tower, a plane to prepare the landing, the pilot to about 100 miles and aircraft communications, through a series of calculations to confirm routes and landing runway, one thousand pilot skull a painful calculate too late, the plane crashed instead of landing, more serious may also involved in a collision with other aircraft. Let’s do it in code.

class Plane = function( name ){ constructor(name){ this.name = name; this.otherPlaneInfo = {}; Calculate (){calculate(let k in this.otherplaneinfo){calculate(let k in this.otherplaneinfo){calculate(let k in this.otherplaneinfo){calculate(let k in this.otherplaneinfo){calculate(let k in this.otherplaneinfo){calculate(let k in this.otherplaneinfo){ } this.send(msg, this.otherPlaneInfo[plane.name].plane); } send(MSG,plane){// Send a message to the pilot of another plane. } receive(MSG,plane){this.otherPlaneinfo [plane.name] = {MSG,plane,}; this.calculate(); },} const plane1=new Plane(' Orient Airlines 001 '); Const plane2=new Plane(' Orient Airlines 002 '); Send (' I want to land ',plane1); Send (' I want to take off ',plane2);Copy the code

When there are so many planes within 100 kilometers, these planes form a network of many-to-many relationships. With the control tower, the pilot of each plane only needs to communicate with the control tower, becoming a one-to-one relationship. As a mediator, the control tower knows the flight status of each plane, so it can arrange the takeoff and landing times of all planes and make timely course adjustments.

This scenario applies the intermediary mode, in which the command Tower is the intermediary. The following code implements this scenario.

class Tower{ constructor(){ this.planeList = []; } addPlane(plane){ this.planeList.push(plane); Calculate (MSG){return result} receive(MSG,plane){let result = this. Calculate (MSG){return result = this. plane.receive(result); // Send a message to the pilot who sends the message to the control tower after the calculation is complete. }, snedAll:function(MSG){this.planelist. ForEach (item =>{item.receive(MSG)})}}; const tower = new Tower(); Class Plane = function(name){constructor(name){this.name = name; Receive (MSG,this)} receive(MSG){console.log(MSG)}, } const plane1=new Plane(' Orient Airlines 001 '); Const plane2=new Plane(' Orient Airlines 002 '); tower.addPlane(plane1); AddPlane (plane2); addPlane(Plane2); Send (' I want to land '); Plane2. Send (' I want to take off ');Copy the code

When to use the mediation pattern

The intermediary pattern is a realization of Demeter principle. Demeter’s principle, also known as the least knowledge principle, states that one subject should know as little as possible about another (similar to not talking to strangers). If the coupling between objects is too high, changes in one object will inevitably affect other objects, just like “fire at the gate brings disaster to the fish in the pond”. In the mediator mode, objects are hardly aware of each other’s existence and can only influence each other through the mediator object.

Thus, the mediator pattern decouples the objects, replacing the mesh many-to-many relationship between objects with a one-to-many relationship between the mediator and the objects. Each object only needs to pay attention to the realization of its own function, and the interaction between objects is handed over to the intermediary object to realize and maintain.

However, there are some drawbacks to the intermediary model. One of the biggest disadvantages is the addition of a mediator object to the system, because the complexity of the interaction between objects is transferred to the complexity of the mediator object, making the mediator object often huge. The intermediary object itself is often a difficult object to maintain, like the control tower at an airport, which has a large and complex workload.

The mediator pattern can be very convenient to decouple objects, but decoupling between objects is not necessarily necessary. In a real project, it is normal to have some dependencies between objects. After all, we write programs to deliver projects quickly, not to overuse design patterns. The key is how to measure the coupling between objects. In general, if the complex coupling between objects does make invocation and maintenance difficult, then we can consider refactoring the code with the mediator pattern.