Created
September 5, 2017 16:55
-
-
Save Kolenov/77e6ee695cfa7d108680dd5e9fb5e1a1 to your computer and use it in GitHub Desktop.
Mediator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//part 1 | |
function Player(name) { | |
this.points = 0; | |
this.name = name; | |
} | |
Player.prototype.play = function () { | |
this.points += 1; | |
mediator.played(); | |
}; | |
var scoreboard = { | |
// HTML element to be updated | |
element: document.getElementById('results'), | |
// update the score display | |
update: function (score) { | |
// playing with DOM | |
} | |
}; | |
// part 2 | |
var mediator = { | |
// all the players | |
players: {}, | |
// initialization | |
setup: function () { | |
var players = this.players; | |
players.home = new Player('Home'); | |
players.guest = new Player('Guest'); | |
}, | |
// someone plays, update the score | |
played: function () { | |
var players = this.players, | |
score = { | |
Home: players.home.points, | |
Guest: players.guest.points | |
}; | |
scoreboard.update(score); | |
}, | |
keypress: function (e) { | |
e = e || window.event; // IE | |
if (e.which === 49) { // key "1" | |
mediator.players.home.play(); | |
return; | |
} | |
if (e.which === 48) { // key "0" | |
mediator.players.guest.play(); | |
return; | |
} | |
} | |
}; | |
//part 3 | |
mediator.setup(); | |
window.onkeypress = mediator.keypress; | |
// game over in 30 seconds | |
setTimeout(function () { | |
window.onkeypress = null; | |
alert('Game over!'); | |
}, 30000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Mediator
Wherefore
Mediator is a behavioral design pattern that allows us to expose a unified interface through which the different parts of a system may communicate.
Howto
Using additional object
Mediator. Pros/Cons
Advantages
weakens the relationship between objects
helps to simplify objects
Disadvantages
system is getting less transparent
performance degradation