前言
发布订阅模式有个亲戚,叫观察者模式,他们比较相似。发布订阅模式是多对多的联系,观察者模式是一对多的联系。
例如,多个老师给多个同学布置作业,这样的场景就需要发布订阅模式来实现了。
模式实现
1 原型方法
var Teacher = function (type) {
this.type = type;
this.pubObjects = [];
}
Teacher.prototype = {
pubObject: function (student) {
if (this.pubObjects.indexOf(student) < 0 && student instanceof Student) {
this.pubObjects.push(student);
}
},
assignWork: function () {
let length = this.pubObjects.length;
for (var i = 0; i < length; i++) {
console.log(this.pubObjects[i].name, " need to do ", this.type);
}
}
}
var Student = function (name) {
this.name = name;
this.objects = [];
}
Student.prototype = {
subObject: function (teacher) {
if (this.objects.indexOf(teacher) < 0 && teacher instanceof Teacher) {
this.objects.push(teacher);
} else {
console.log("had sub it.");
}
},
doWork: function () {
let length = this.objects.length;
for (var i = 0; i < length; i++) {
console.log(this.name, " do ", this.objects[i].type);
}
}
}
2 使用示例
var yw = new Teacher('yw');
var sx = new Teacher('sx');
var xm = new Student('xm');
var xh = new Student('xh');
yw.pubObject(xm);
yw.pubObject(xh);
xm.subObject(yw);
xm.subObject(sx);
yw.assignWork();
xm.doWork();
3 输出结果
xmlxm need to do yw
xh need to do yw
xm do yw
xm do sx