Skip to content
New issue

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

观察者模式和订阅-发布模式的区别 #6

Open
sihai00 opened this issue Jul 19, 2019 · 0 comments
Open

观察者模式和订阅-发布模式的区别 #6

sihai00 opened this issue Jul 19, 2019 · 0 comments
Assignees

Comments

@sihai00
Copy link
Owner

sihai00 commented Jul 19, 2019

区别:

观察者模式:中主体和观察者是互相感知的
发布订阅模式:借助第三方来实现调度的,发布者和订阅者之间互不感知
区别

代码

观察者模式

var subject = {
    observers: [],
    notify() {
        this.observers.forEach(observer =>{
	     observer.update()
        })
    },
    attach (observer) {
        this.observers.push(observer)
    }
}
var observer = {
    update(){
	alert('updated')
    }
}
subject.attach(observer)
subject.notify()

发布订阅模式

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)

参考

介绍下观察者模式和订阅-发布模式的区别,各自适用于什么场景

@sihai00 sihai00 self-assigned this Jul 19, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant