Skip to content

Instantly share code, notes, and snippets.

@KalpasWang
Created December 26, 2019 15:16
Show Gist options
  • Save KalpasWang/8519c39e9aad3d21367132f5066bb204 to your computer and use it in GitHub Desktop.
Save KalpasWang/8519c39e9aad3d21367132f5066bb204 to your computer and use it in GitHub Desktop.
中介者模式
<!DOCTYPE html>
<!-- saved from url=(0046)http://www.jspatterns.com/book/7/mediator.html -->
<html><head><meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Mediator pattern</title>
<style>
#results {text-align: center; font-size: 100px;}
strong {color: blue;}
</style>
</head>
<body cz-shortcut-listen="true">
<p>Player one press "1", player two press "0". Go! (you have half a minute...)</p>
<div id="results"></div>
<script>
// player constructor
function Player(name) {
this.points = 0;
this.name = name;
}
// play method
Player.prototype.play = function () {
this.points += 1;
mediator.played();
};
// the scoreboard object
var scoreboard = {
// HTML element to be updated
element: document.getElementById('results'),
// update the score display
update: function (score) {
var i, msg = '';
for (i in score) {
if (score.hasOwnProperty(i)) {
msg += '<p><strong>' + i + '<\/strong>: ';
msg += score[i];
msg += '<\/p>';
}
}
this.element.innerHTML = msg;
}
};
var mediator = {
// all the players
players: {},
//
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);
},
// handle user interactions
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;
}
}
};
// go!
mediator.setup();
window.onkeypress = mediator.keypress;
// game over in 30 seconds
setTimeout(function () {
window.onkeypress = null;
alert('Game over!');
}, 30000);
</script>
<div class="xl-chrome-ext-bar" id="xl_chrome_ext_{4DB361DE-01F7-4376-B494-639E489D19ED}" style="display: none;">
<div class="xl-chrome-ext-bar__logo"></div>
<a id="xl_chrome_ext_download" href="javascript:;" class="xl-chrome-ext-bar__option">&#19979;&#36733;&#35270;&#39057;</a>
<a id="xl_chrome_ext_close" href="javascript:;" class="xl-chrome-ext-bar__close"></a>
</div></body></html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment