Observer/published subscriber mode
This is the third day of my participation in the August More Text Challenge. For details, see “August More Text Challenge”.
What is observer mode? The official definition is:
Defines a one-to-many dependency between objects so that when an object’s state changes, all dependent objects are notified and automatically updated. All observers that depend on the target object will be notified when the properties of the target object change.
// The target object
class Subject {
constructor () {
this.observers = []
}
// Add an observer
add (observer) {
return this.observers.push(observer)
}
// Remove the observer
remote (observer) {
this.observers = this.observers.filter(e= >e ! == observer) }// Send a message to notify the observer
notify () {
this.observers.forEach(item= > item.update())
}
}
// The observer object
class Observer {
constructor (name) {
this.name = name
}
// Update notification
update () {
console.log(`my name is The ${this.name}`)}}const sub = new Subject()
const obs1 = new Observer('rudy')
const obs2 = new Observer('kobe')
sub.add(obs1)
sub.add(obs2)
sub.notify()
// my name is rudy
// my name is kobe
Copy the code
Publish and subscribe this pattern:
Just like children in school, there are many subjects. Each subject teacher acts as a publisher, and a group of children acts as subscribers. Each teacher is a different instance function, Posting tasks and assignments without affecting anyone else.
class Subject {
constructor () {
// List of topics
this.observers = {}
}
// Add a subscription
on (key, fn) {
if (!this.observers[key]) {
this.observers[key] = []
}
this.observers[key].push(fn)
}
// Unsubscribe
off (key) {
delete this.observers[key]
}
// Issue a notification
emit (key, params) {
if (!this.observers[key]) return
const arr = this.observers[key]
/ / execution
arr.forEach(item= > item(params))
}
}
// A single theme
const sub = new Subject()
sub.on('math'.(sub) = > {
console.log('I'm on it${sub}Class `)
})
sub.on('english'.(sub) = > {
console.log('I'm on it${sub}Class `)
})
sub.emit('math'.'mathematics') // I'm having a math class
sub.emit('english'.'English') // I'm in English class
Copy the code
The difference between the two modes
- The published subscriber pattern has a message manager in the middle compared to the observer pattern, resulting in less coupling between the publisher and the subscriber.
- The observer mode is usually used for
synchronous
Scenario, and the published subscriber pattern is usually used forasynchronous
Scenario (listening callback)
Stolen figure ~ ~ ~