mituri

[JS] Wzorzec Mediator

Apr 19th, 2018
257
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.42 KB | None | 0 0
  1. console.clear();
  2. var cl = function(text){ console.log(text); }
  3.  
  4. var Participant = function(name){
  5. this.name = name;
  6. this.chatroom = null;
  7. };
  8.  
  9. Participant.prototype = {
  10. send: function(message, to) {
  11. this.chatroom.send(message, this, to);
  12. },
  13. receive: function(message, from) {
  14. log.add(from.name + ' to ' + this.name + ': ' + message);
  15. }
  16. };
  17.  
  18. var log = (function(){
  19. var log = "";
  20.  
  21. return {
  22. add: function(msg) {
  23. log += msg + "\n";
  24. },
  25. show: function() {
  26. console.log(log);
  27. log = "";
  28. }
  29. };
  30. })();
  31.  
  32. var ChatroomMediator = function() {
  33. var participants = {};
  34.  
  35. return {
  36. register: function(participant) {
  37. participants[participant.name] = participant;
  38. participant.chatroom = this;
  39. },
  40. send: function(message, from, to) {
  41. if (to) {
  42. to.receive(message, from);
  43. } else {
  44. var key;
  45. for (key in participants) {
  46. if (participants[key] !== from) {
  47. participants[key].receive(message, from);
  48. }
  49. }
  50. }
  51. }
  52. };
  53. };
  54.  
  55.  
  56. (function run(){
  57. var yoko = new Participant('Yoko');
  58. var john = new Participant('John');
  59. var paul = new Participant('Paul');
  60.  
  61.  
  62. var chatroom = new ChatroomMediator();
  63. chatroom.register(yoko);
  64. chatroom.register(john);
  65. chatroom.register(paul);
  66.  
  67. yoko.send('all you need is love');
  68. yoko.send('I love you John');
  69. john.send("Hey, no need to broadcast", yoko);
  70. paul.send("Ha, I heard that!");
  71.  
  72. log.show();
  73. })();
Advertisement
Add Comment
Please, Sign In to add comment