js中介者模式是什么意思?
js中介者模式是什么意思?
现实生活中,航线上的飞机只需要与机场的塔沟通就可以确定航线和飞行状态,而不需要与所有飞机沟通。同时,塔作为中介,知道每架飞机的飞行状态,可以安排所有飞机的起降和航线。
概念
1、通过一个中介对象,所有其他相关对象都通过中介对象通信,而不是相互引用。
2、当一个对象发生变化时,只需通知中介对象。通过中介模式,可以解除对象与对象之间的耦合关系。
实例
JavaScript
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<p>1 0 30</p>
<div id="results"></div>
<script>
//Mediator
//这里用了构造器模式
function Player(name) {
this.name = name;
this.point = 0;
}
Player.prototype.play = function() {
this.point += 1;
mediator.played();
}
var scoreboard = {
ele : 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.ele.innerHTML = msg;
}
};
var mediator = {
players : {},
setup : function() {
var player = this.players;
player.home = new Player("Home");
player.guest = new Player("Guest");
},
played : function() {
var player = this.players;
score = {
Home : player.home.point,
Guest : player.guest.point
};
scoreboard.update(score);
},
keypress : function(e) {
e = e || window.event; //事件监听
if(e.which === 49) {
mediator.players.home.play();
}
if(e.which === 48) {
mediator.players.guest.play();
}
}
};
mediator.setup();
window.onkeypress = mediator.keypress;
setTimeout(function(){
window.onkeypress = null;
console.log("game over!");
}, 30000);
</script>
</body>
</html>
以上就是js中介者模式的意思,希望对大家有所帮助。