The Mediator Pattern in JavaScript

Christopher T.

October 27th, 2019

Share This Post

In this article, we will be going over the mediator pattern and implementing one using JavaScript. Mediators in JavaScript allow us to expose a central interface that encapsulates all of the interactions between a set of objects.

Because this pattern alters a program's running behavior and is responsible for coordinating interactions, it is considered a behavioral pattern.

As your app grows in size, the need to introduce a mediator grows more in demand if you have multiple objects directly interacting with each other.

Pretend that you are half way finished into developing an RPG game and designed a bunch of classes or functions that didn't make use of the mediator pattern. Let's take a look and see what that can look like:

clutter classes mediator pattern in javascript

Now try and imagine yourself trying to read and maintain the code that lies underneath. You would have to track everything on your own and be aware who function1 communicates with, that function3 communicates with function9, function5 communicates with function10, function8 receives data from function10 and relays it to function2, etc. Surely this would quickly become a developer's worst nightmare!

When introducing the mediator pattern to this code, the mediator object would be placed somewhere in-between and its main responsibility is to encapsulate all that interaction and behavior between them, designating itself the responsibility of handling all that on its own.

This would look something like this:

mediator pattern javascript more organized

As you can now see, the mediator object sits in between and is now the one responsible for the interactions between the set of objects. Now imagine debugging this app. If one of the modules here throws an error, we know that the only two places to look is the mediator or the module itself. This makes it easier to maintain a larger code base since we're able to separate logic more distinctively.

In addition, we can ensure that it will become much less of a hassle than before when we need to change something in the code, since we now have a clearer picture of the direction between objects.

How do we know when it's time to introduce the Mediator Pattern?

The need to introduce this may occur when something in the code ends up having too many direct relationships with other parts. At this point your code would probably be unstable. It helps to promote loose coupling between them by ensuring that instead of them referring to other objects explicitly, all of their interactions would be coordinated through a central point which would be the mediator. This helps us improve the usability of our components.

Real World Analogy

Here's one real world analogy that might help you understand how a mediator helps to bring efficiency and the concept of it:

You're in a class room with other students and the teacher has a stack of papers with her. She wants to get these passed out so that every student receives one. Instead of your teacher handing out a stack of papers to a student to have them take one and passing the stack to the student behind them until the last student receives the stack, she decides to just pass the papers down to each student herself. From this, she's responsible for ensuring that every child gets a piece of a paper and essentially takes on the role of a mediator. At the end when the the last student is reached, another student across the room raises his hand and says "I didn't get a piece of paper". Now you try to "debug" this situation. You can immediately come to the conclusion that the mediator was responsible for the missing paper since her role was to provide every student a piece of paper. In addition, you also have a clear prediction on where the stack of paper is currently located at this point.

Now if the teacher decided to pass the stack down to the students where the sudents are responsible for ensuring that they all get a piece of paper, and a student raises up their hand saying they didn't get a paper, "debugging" this situation would be rather difficult. First, you don't know where the stack of papers are located at this point. Second, you have almost no idea who messed up the process. You would have to ask every student and ask them who they handed their stack to in order to figure out how someone didn't get paper.

If you've been developing for the web on JavaScript, then you've already been developing around mediators. In the DOM, an example of a mediator is the document object itself, since it can coordinate the logic and behavior between DOM elements in it. An input element with type="radio" can also be a mediator, as it can decide which radio to check since it can hold the current value.

Advantages

When you have multiple objects that are communicating directly with each other, your essentially working around a many to many relationship which can become a nightmare when debugging. Introducing the mediator will help reduce this issue by introducing a one to many flow between objects.

Other notable benefits include reducing dependencies between objects (loose coupling), much lighter errors, increased ease with code maintainability and readability.

Disadvantages

As with all beautiful things in life, not everything is perfect. Same goes for the mediator pattern.

For example, having one single point of object to coordinate all of the interactions between objects essentially means that if there were any bugs it would affect everything that is encapsulated by it. One example of that can be that since mediators are the central point of interactions between multiple objects, it may become a performance issue as your app gets larger as they are always communicating indirectly.

However, choosing between having a mediator manage the interactions as opposed to objects doing it directly with one another will almost always be the better choice. If we change something in one of the objects and something ends up throwing an exception, it can easily create a domino effect throughout the rest of your application and you will have a hard time knowing where to even begin. Just like our real world analogy in an earlier example, it would become a real nightmare to debug this situation as you would have to check each point of communication in your code.

Code Example

Lets pretend that we are creating an RPG game and the very first features we would like to implement are a Novice class, and implementing a party api. If you've never heard of this concept of a party, it's when you associate one or more group of users together to create an allied team to accomplish a specific goal together.

We will define a Novice constructor as well as the Game and Party. The Novice is used to create new players, the Party provides an API for the party functionality, and the Game will become the mediator that will use Party to create the associations between Novice instances (users).

Here is a code example of this in action:

function createId() {
  const S4 = function() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
  }
  return (
    S4() +
    S4() +
    '-' +
    S4() +
    '-' +
    S4() +
    '-' +
    S4() +
    '-' +
    S4() +
    S4() +
    S4()
  )
}

function Novice(name) {
  this.name = name
  this.hp = 100
  this.id = createId()
  this.party = null
}

Novice.prototype.attack = function(target, hp) {
  target -= hp
  return this
}

const roy = new Novice('roy')
const ben = new Novice('ben')
const lucy = new Novice('lucy')
const sally = new Novice('sally')

function Party(leader, ...members) {
  this.id = createId()
  this.leader = leader
  this.members = members
}

function Game(options) {
  this.parties = {}

  if (options) {
    // do stuff
  }
}

Game.prototype.createParty = function(leader, ...members) {
  const party = new Party(leader, ...members)
  this.parties[party.id] = party
  leader.party = party
}

Game.prototype.removeParty = function(leader) {
  delete this.parties[leader.party.id]
  leader.party = null
}

const game = new Game()
game.createParty(roy, ben, lucy)

As we can see from the example, designating the Game instances to coordinate the party associations between multiple users makes the code a lot easier to read and maintain and it decouples logic between Party and Novice instances.

Otherwise, we'd have to directly implement the logic as party of either the Novice or Party interface, which doesn't make much sense to merge them if that was the case. And when things don't make sense, it makes it more difficult to debug if an issue were to occur!

Conclusion

And that concludes the end of this point! I hope you found this to be valuable and look out for more in the future!


Tags


Subscribe to the Newsletter
Get continuous updates
© jsmanifest 2020