concept
The observer Pattern, also known as the Publish/Subscribe Pattern, is a behavioral Pattern
A subject maintains a set of observers, and when the state of the observed object changes, it notifies the observer of these changes by calling one of the observer’s methods.
The key point
- Subscribe to the function
- unsubscribe
- Publish functionality (trigger event)
Real example
- You subscribe to a blogger’s channel and receive notifications when content is updated;
- Event subscription response mechanism in JavaScript;
- The relationship between fans and idols. Your idol is the observed, and you, as a fan, are the observer.
implementation
class Subscribe{
constructor(){
// Create a container
this.pool = new Map()}// Create a subscriber
addSubscribe(key, func){
this.pool.set(key,func)
}
// Unsubscribe
removeSubscribe(key){
this.pool.delete(key)
}
// Trigger (broadcast)
broadcast(){
const [key,...rest] = [...arguments];
if(this.pool.has(key)){
const func = this.pool.get(key)
func.apply(this, rest)
}
}
}
const subscribe = new Subscribe();
subscribe.addSubscribe('event1'.function(param){
console.log('New value published',param)
})
subscribe.broadcast('event1'.1);
subscribe.broadcast('event1'.2);
subscribe.broadcast('event1'.3);
subscribe.removeSubscribe('event1');
subscribe.broadcast('event1'.3);
Copy the code
The execution result
I published the new value 1, I published the new value 2, I published the new value 3Copy the code
Please give it a thumbs up, 😳