javascript设计模式之中介者模式

/* 
 * 小游戏演示中介者模式
 * Home 按键 1
 * Guest 按键 0
 * 半分钟内看谁按下的次数多
 *
 * 参与的对象:
 *   玩家
 *   计分板
 *   中介者
 *
 * 中介者模式使对象之间松耦合,提高了可维护性
*/

// 玩家
var Player = function (name) {
    this.name = name;
    this.point = 0;
};

Player.prototype.play = function () {
    this.point += 1;
    mediator.played(); // 每次玩家按键,中介者更新计分板
};

// 计分板
var scoreboard = {

    element: document.getElementById("result"), // 记录比分

    update: function (score) {
        var msg = "",
            i;
        for (i in score) {
            if (score.hasOwnProperty(i)) {
                msg += '<p><strong>' + i + '</strong>: ' + score[i] + '</p>';
            }
        }

        this.element.innerHTML = msg;
    }
};

// 计分人(中介者)
var mediator = {

    // 所有的玩家(player 对象)
    players: {},

    // 玩家就位
    setup: function () {

        var players = this.players;
        players.home = new Player("Home");
        players.guest = new Player("Guest");
    },

    // 计分
    played: function () {
        var players = this.players,

            score = {
                Home: players.home.point,
                Guest: players.guest.point
            };

        scoreboard.update(score);
    },

    // 游戏开始
    keypress: function (e) {

        e = e || window.event;

        if (e.which === 49) { // 按键1
            mediator.players.home.play();
            return;
        } 

        if (e.which === 48) {
            mediator.players.guest.play();
            return;
        }
    }
};


// 运行游戏
mediator.setup();
window.onkeypress = mediator.keypress;

// 游戏在30秒内结束
setTimeout(function () {
    window.onkeypress = null;
    alert("Game Over!");
}, 30000);

 

posted @ 2014-10-15 16:03  farawayfromhome  阅读(310)  评论(0编辑  收藏  举报