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);
相關文章
相關標籤/搜索