Advertisement
Guest User

Untitled

a guest
Apr 21st, 2019
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* Mediator Design Pattern */
  2.  
  3. var Participant = function(name) {
  4.   this.name = name;
  5.   this.chatroom = null;
  6. };
  7.  
  8. Participant.prototype = {
  9.   send: function(message, to) {
  10.     this.chatroom.send(message, this, to);
  11.   },
  12.   receive: function(message, from) {
  13.     console.log(from.name + " to " + this.name + ": " + message);
  14.   }
  15. };
  16.  
  17. var Chatroom = function() {
  18.   var participants = {};
  19.  
  20.   return {
  21.     register: function(participant) {
  22.       participants[participant.name] = participant;
  23.       participant.chatroom = this;
  24.     },
  25.  
  26.     send: function(message, from, to) {
  27.       if (to) {
  28.         // single message
  29.         to.receive(message, from);
  30.       } else {
  31.         // broadcast message
  32.         for (key in participants) {
  33.           if (participants[key] !== from) {
  34.             participants[key].receive(message, from);
  35.           }
  36.         }
  37.       }
  38.     }
  39.   };
  40. };
  41.  
  42. var beau = new Participant("Beau");
  43. var quincy = new Participant("Quincy");
  44. var rafael = new Participant("Rafael");
  45. var berkeley = new Participant("Berkeley");
  46. var evaristo = new Participant("Evaristo");
  47.  
  48. var chatroom = new Chatroom();
  49. chatroom.register(beau);
  50. chatroom.register(quincy);
  51. chatroom.register(rafael);
  52. chatroom.register(berkeley);
  53. chatroom.register(evaristo);
  54.  
  55. quincy.send("How's it going?");
  56. beau.send("The YouTube channel is up to 1 million subscribers!", quincy);
  57. rafael.send("The FCC wiki is more popular than Wikipedia!", quincy);
  58. evaristo.send("98% of our graduates got their dream job!", quincy);
  59. berkeley.send("The government forked our repo and is now using it to create world peace!", quincy);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement