Page 144 - JavaScript
P. 144

var jane = new Employee('Jane');
         var meetingAlerts = new Subject();
         meetingAlerts.registerObserver(bob);
         meetingAlerts.registerObserver(jane);
         meetingAlerts.notifyObservers('4pm');

         // Output:
         // Bob: There is a meeting at 4pm
         // Jane: There is a meeting at 4pm



        Mediator Pattern


        Think of the mediator pattern as the flight control tower that controls planes in the air: it directs this
        plane to land now, the second to wait, and the third to take off, etc. However no plane is ever
        allowed to talk to its peers.

        This is how mediator works, it works as a communication hub among different modules, this way
        you reduce module dependency on each other, increase loose coupling, and consequently
        portability.


        This Chatroom example explains how mediator patterns works:


         // each participant is just a module that wants to talk to other modules(other participants)
         var Participant = function(name) {
             this.name = name;
             this.chatroom = null;
         };
          // each participant has method for talking, and also listening to other participants
         Participant.prototype = {
             send: function(message, to) {
                 this.chatroom.send(message, this, to);
             },
             receive: function(message, from) {
                 log.add(from.name + " to " + this.name + ": " + message);
             }
         };

          // chatroom is the Mediator: it is the hub where participants send messages to, and receive
         messages from
         var Chatroom = function() {
             var participants = {};

             return {

                 register: function(participant) {
                     participants[participant.name] = participant;
                     participant.chatroom = this;
                 },

                 send: function(message, from) {
                     for (key in participants) {
                         if (participants[key] !== from) {//you cant message yourself !
                             participants[key].receive(message, from);
                         }
                     }
                 }




        https://riptutorial.com/                                                                             101
   139   140   141   142   143   144   145   146   147   148   149