观察者模式和发布订阅模式
观察者模式:是指一个对象(subject)维持一个依赖列表Observer,当主题状态发生变化的时候,会通知观察者集合。发布和观察者都能看到对方都知道对方的存在。比如事件触发。
发布订阅模式:观察者和订阅者关联。发布消息发出到消息接收订阅者。需要通过第三方信息中介:观察者。所以有发布者 ,观察者,订阅者。发布者发布消息,订阅者不能直接收到消息需要经过观察者通知。比如消息队列
然而在代码的世界里,没有代码解释,世界是苍白的。
所以
观察者模式
js1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| var subject = { observers:[], notify(){ this.observers.forEach(observer=>{ observer.update() }) }, attch(observer){ this.observers.push(observer) } }
var observer = { update(){ console.log('updated!!!') } } subject.attch(observer) subject.notify()
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| function Subject(){ this.observers = [] } function Observer(name){ this.name = name }
Subject.prototype ={ add: function(observer){ this.observers.push(observer) }, remove: function(observer){ var o = this.observers o.forEach(el=>{ if(el === observe){ o.splice(el,1) } }) }, notify: function(){ this.observers.forEach(o=>{ o.update() }) } }
Observer.prototype ={ update: function(){ console.log('my name is '+this.name) } }
var Sub = new Subject() var Obs = new Observer('lxs')
Sub.add(Obs) Sub.notify()
|
发布订阅者模式
js1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| var publisher = { publish(pubsub){ pubsub.publish() } }
var pubsub = { subscribes:[], publish(){ this.subscribes.forEach(subscribe=>{ subscribe.update() }) }, subscribe(sub){ this.subscribes.push(sub) } } var subscribe = { update(){ console.log('update!!!') }, subscribe(pubsub) { pubsub.subscribe(this); } } subscribe.subscribe(pubsub) publisher.publish(pubsub)
|