JavaScript設計模式-- 中介者(mediator)模式
定義: 當物件彼此間的交互作用太過複雜時, 可透過某一物件(中介者)來處理, 也就是透過減少物件間的耦合程度。(所有物件中的互動皆透過中介者傳遞)。
e.g.
function Player(name) {
this.points = 0;
this.name = name;
}
Player.prototype.play = function() { // 用來表示得分
this.points += 1;
mediator.played(); // 告訴中介者自己(每個物件)加完分了
};
var scoreboard = { // 用來顯示分數的UI
element: document.body, // 因為了輸出到網頁上
update: function(score) {
var i, msg = "";
for (i in score) { // 不確定有多少物件屬性-->所以跑for/in loop
if (score.hasOwnProperty(i)) { // 因只找該物件本身的屬性, 不找原型鏈上(__proto__)的
msg += "<p><strong>" + i + "</strong>:";
msg += score[i];
msg += "</p>";
}
}
this.element.innerHTML = msg;
}
};
var mediator = {
Players: {}, // 用來存放(註冊)所有玩家的物件
add: function(key, obj) { // 可持續動態新增多個玩家
this.Players[obj.name] = { // 使key和玩家名能成為一組組的關係。(方便確認各個key和玩家名的對應關係)
key: key,
obj: obj
};
},
played: function() {
var score = {};
for (var player in this.Players) {
score[player] = this.Players[player].obj.points; // 為了把分數放在score物件上
}
scoreboard.update(score); // 更新資料、
},
keypress: function(e) {
e = e || window.event;
for (var player in mediator.Players) {
player = mediator.Players[player];
if (e.which === player.key) {
player.obj.play();
return;
}
}
}
};
mediator.add(48, new Player("Home"));
mediator.add(49, new Player("Guest"));
mediator.add(50, new Player("Other"));
mediator.add(51, new Player("Mark"));
mediator.add(52, new Player("John"));
window.onkeypress = mediator.keypress; // 定義event, 指向mediator的keypress方法
p.s. 下篇討論一下 which/ keyCode/ charCode的差別喔!
e.g.
function Player(name) {
this.points = 0;
this.name = name;
}
Player.prototype.play = function() { // 用來表示得分
this.points += 1;
mediator.played(); // 告訴中介者自己(每個物件)加完分了
};
var scoreboard = { // 用來顯示分數的UI
element: document.body, // 因為了輸出到網頁上
update: function(score) {
var i, msg = "";
for (i in score) { // 不確定有多少物件屬性-->所以跑for/in loop
if (score.hasOwnProperty(i)) { // 因只找該物件本身的屬性, 不找原型鏈上(__proto__)的
msg += "<p><strong>" + i + "</strong>:";
msg += score[i];
msg += "</p>";
}
}
this.element.innerHTML = msg;
}
};
var mediator = {
Players: {}, // 用來存放(註冊)所有玩家的物件
add: function(key, obj) { // 可持續動態新增多個玩家
this.Players[obj.name] = { // 使key和玩家名能成為一組組的關係。(方便確認各個key和玩家名的對應關係)
key: key,
obj: obj
};
},
played: function() {
var score = {};
for (var player in this.Players) {
score[player] = this.Players[player].obj.points; // 為了把分數放在score物件上
}
scoreboard.update(score); // 更新資料、
},
keypress: function(e) {
e = e || window.event;
for (var player in mediator.Players) {
player = mediator.Players[player];
if (e.which === player.key) {
player.obj.play();
return;
}
}
}
};
mediator.add(48, new Player("Home"));
mediator.add(49, new Player("Guest"));
mediator.add(50, new Player("Other"));
mediator.add(51, new Player("Mark"));
mediator.add(52, new Player("John"));
window.onkeypress = mediator.keypress; // 定義event, 指向mediator的keypress方法
p.s. 下篇討論一下 which/ keyCode/ charCode的差別喔!
留言
張貼留言