Front-end developers may not make the distinction between the observer model and the subscriber model, but what I feel is the observer model
define
When there is a one-to-many dependency between objects, all dependent objects (observer objects) are notified and automatically updated when the state of one object changes
Life scenes
For example, wechat circle of friends, Secretary Li li, Begonia blossoming, Lin Waner have added fan Xian friends, and pay attention to his circle of friends, at this time fan Xian released a dynamic want to eat chicken legs, three girls see immediately to buy…
Above case fan xian is the publisher
// Create a love bean class
class AiDou {
constructor(id, name) {
this.name = name
this.id = id
this.friends = []
}
// Pay attention to him, let him live, let him live...
addFriend(person) {
if (!this.friends.includes(person)) {
this.friends.push(person)
}
}
// Can't fall in love
remove(person) {
for (let i in this.friends) {
if (person === this.friends[i]) {
this.friends.splice(i, 1)}}}// Notify female fans
notify(msg) {
this.friends.map(item= > {
item.update(this.name + msg + ', go and like it!! Go!! ')}}}Copy the code
The three girls are the observers
class Observer {
constructor(id, name){
this.id = id
this.name = name
}
// Refresh your moments
update(msg) {
console.log(msg)
}
}
const SLL = new Observer(1.'Silili')
const HTDD = new Observer(2.'Crabapple blossoming')
const LWE = new Observer(3.'Wan 'er Lin')
Copy the code
The next step is to pick up Aidou, scan it (QR code) and take it away
const FX = new AiDou(0.'such')
// add Lin waner first
FX.addFriend( LWE )
// Continue to add logic
FX.addFriend( SLL )
// Add crabapple
FX.addFriend( HTDD )
Copy the code
Finally, it’s a long wait. Wait for what? Waiting for love bean to give a thumbs-up!!
After a year of waiting, the female fans almost lost their hair, this time finally aidou hair new song, please come to listen!!
FX.notify('There's a new song out.') // All fans have received the message: Fan Xian has released a new song, please give it a thumbs up!! Go!!
Copy the code
And finally, a classic picture, a classic example of the observer model
summary
When I was writing this article, I thought for a long time about how to write this design model so that it could be simple and easy to understand, and finally come back to the living example
The design Patterns series will probably come to an end. I will update it from time to time and start a new chapter soon
The last whisper
Why do so many beverage ingredients list sodium: Is there a certain level of sodium in the body that keeps you hydrated