很多时候无可奈何,我无法改变很多。。我以为可以改变,只要我愿意--像是一个个的轮回,死而复生,心死复生的喜悦。可是再一次,我宁愿那颗心从未苏醒。。。
若是要一定是一座浮萍,要是可以自由的,快乐的,我在所不惜--
中介者模式通过解耦来提高代码可维护性
// player function Player(name){ this.points = 0; this.name = name; } Player.prototype.play = function(){ this.points += 1; mediator.played(); }; // scoreboard var scoreboard = { // 待更新的HTML元素 element : document.getElementById("results"), // 更新得分显示 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 = { // 所有的玩家(player对象) players : {}, // 初始化 setup : function(){ var players = this.players; players.home = new Player(); players.guest = new Player(); }, // 如果有人玩,则更新得分值 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; if(e.which === 49){ mediator.players.home.play(); return; } if(e.which === 48){ mediator.players.guest.play(); } } }; mediator.setup(); window.onkeypress = mediator.keypress; // 游戏在30s内结束 setTimeout(function(){ window.onkeypress = null; alert("Game's over!"); }, 30000);
说明:
1. Player对象(用来创建玩家们)
2. scoreboard对象(用来更新显示)
3. mediator中介者(setup: 用Player 创建players; keypress : 绑定键盘事件- 更新player的分数并通知scoreboard 界面更新)