中介设计模式

另一个设计模式,正如其名称所暗示的那样,是中介,起着调解作用。这种模式为一组对象提供了一个中心控制点。它被大量用于状态管理。当其中一个对象更改其属性的状态时,中介可以轻松地将其广播给其他对象。
下面是一个简单的例子,说明 Mediator 设计模式如何提供帮助:
var Participant = function (name) {
this.name = name;
this.chatroom = null;
}
Participant.prototype.receive = function() {
}
//define a Itprototype for participants with receive and send implementation
var Talkie = function () {
var participants = {};
return {
register: function (participant) {
participants[participant.name] = participant;
participant.talkie = this;
},
send: function (message, from, to) {
if (to) { // single message
to.receive(message, from);
} else { // broadcast message
for (key in participants) {
if (participants[key] !== from) {
participants[key].receive(message, from);
}
}
}
}
};
};
function letsTalk() {
var A = new Participant("A");
var B = new Participant("B");
var C = new Participant("C");
var D = new Participant("D");
var talkie = new Talkie();
talkie.register(A);
talkie.register(B);
talkie.register(C);
talkie.register(D);
talkie.send("I love you B.");
talkie.send("No need to broadcast", A);
talkie.send("Ha, I heard that!");
talkie.send("C, do you have something to say?", C);
}
总结:
我们的中介者在此模式中起着一个中心点的角色,它负责将参与者储存起来,然后将参与者的信息转发出去。实现了一个单播和多播的功能。