We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
很多文章认为:观察者模式===发布订阅模式。 这个结论有待商榷。至少代码层面是不一样的。
每个实例都有发布任务(publish)和订阅任务(subscribe)的能力。且都各自维护自己的任务列表,列表中存储订阅自己的个体信息。
//假设有个学生群体,有A,B,C,D四个学生,A,B,C同时订阅D。D发布信息时,A,B,C给予响应。 class Student { constructor(name) { this.name = name; this.list = [] } subscribe(target, callback) { target.list.push(callback) } publish(params) { this.list.forEach(func => func(params)) } } const stuA = new Student("A") const stuB = new Student("B") const stuC = new Student("C") const stuD = new Student("D") //stuA,stuB,stuC 分别观察stuD。并传入相应的回调函数 stuA.subscribe(stuD, function (params) { console.log("A receive D:" + params) }) stuB.subscribe(stuD, function (params) { console.log("B receive D:" + params) }) stuC.subscribe(stuD, function (params) { console.log("C receive D:" + params) }) stuD.publish('send a message')
有一个事件管理中心,订阅者把自己想订阅的事件注册在事件管理中心,发布者发布事件时,由管理中心统一触发订阅者注册的事件。
//事件管理中心 const union = { eventObj:{}, subscribe: function (type, callback) { if (!this.eventObj[type]) { this.eventObj[type] = [] } this.eventObj[type].push(callback) }, publish: function (type, ...items) { const callbacks = this.eventObj[type] if (callbacks) { callbacks.forEach(callback => { callback.apply(null, items) }); } } } class Student { constructor(name) { this.name = name; } subscribe(type, callback) { union.subscribe(type,callback) } publish(type,params) { union.publish(type,params) } } const stuA = new Student("A") const stuB = new Student("B") const stuC = new Student("C") const stuD = new Student("D") //stuA,stuB,stuC 分别订阅事件‘demo'。并传入相应的回调函数 stuD触发该事件 stuA.subscribe('demo', function (params) { console.log("A receive D:" + params) }) stuB.subscribe('demo', function (params) { console.log("B receive D:" + params) }) stuC.subscribe('demo', function (params) { console.log("C receive D:" + params) }) stuD.publish('demo','simple demo')
The text was updated successfully, but these errors were encountered:
No branches or pull requests
很多文章认为:观察者模式===发布订阅模式。 这个结论有待商榷。至少代码层面是不一样的。
观察者模式
每个实例都有发布任务(publish)和订阅任务(subscribe)的能力。且都各自维护自己的任务列表,列表中存储订阅自己的个体信息。
发布订阅模式
有一个事件管理中心,订阅者把自己想订阅的事件注册在事件管理中心,发布者发布事件时,由管理中心统一触发订阅者注册的事件。
参考文献
The text was updated successfully, but these errors were encountered: