JavaScript设计模式之中介模式

中介者模式

该模式会缓解对象之间的耦合度,将紧耦合转换成松耦合

代码示例,实现一个键盘游戏,有两个玩家。规定一个人按‘1’,一个人按‘0’。

//玩家对象
function Player (name) {
    this.points = 0;
    this.name = name;
}
Player.prototype.play = function () {
    this.points += 1;
    mediator.played();//调用中介者的方法
}

//计分板对象
scoreBoard = {
    element: document.getElementById('result'),
    update: function (score) {
        var I,msg = '';

        for(I in score){  
            if(score.hasOwnProperty(i)){  
              //对msg显示字符串的处理
              msg += ...
            }
        }
        this.element.innerHtml = msg;
    }
};
//中介者对象
var mediator = {
    //包含通信双方的对象
    players: {},
    //初始化
    step: function () {
        //创建两个玩家
        var players = this.players;
        players.home = new PLayer('Home');
        players.guest = new PLayer('Guest');
    },
    played: function () {  
      var players = this.players;

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

      mediator.update(score);
    },
    keypress: function (e) {  
      e = e || window.event;
      if(e.which === 49){  //按键‘1’
          mediator.players.home.play();
          return;
        }
        if(e.which === 48){  //按键‘0’
          mediator.players.guest.play();
          return;
        }
    }
};

//建立和拆除游戏
Mediator.step();
Window.onkeypress = mediator.keypress;//监听键盘事件

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

你可能感兴趣的:(前端技术,js)