“This is the second day of my participation in the November Gwen Challenge. See details of the event: The last Gwen Challenge 2021”.
Recently I learned a paragraph in my study: When learning something, you can follow what it is, what it is useful, what its advantages are, what its disadvantages are, how to use it, or what to pay attention to when using it. I think these five pieces are still very useful, can help you quickly master a knowledge point
What is the observer model?
Defines a one-to-many relationship between objects that notifies dependent observers of automatic updates when the observed changes
Not long ago, we just learned the observer mode. Our teachers told us that to understand the observer mode, we can relate to examples in reality. There are many examples of the observer mode around us. For example, in the recent Double 11, I believe that more or less everyone got some discount coupons. Between us and each merchant, it can be an observer model.
Specific is when the businessman issues a few discount roll, can inform you directly through app, and do not need you to crouch shop all the time, see it is not to send discount roll ah this way. All you have to do is wait for a notification from your phone app.
So how is the observer model reflected in this. First of all, a business can correspond to many consumers, so the business is the observed, the consumer is the observer, the observer will be notified when the change is made, is when the business issued a coupon will be notified to pay attention to his consumers to buy things.
What’s the use of observer mode?
– Solved the problem of how one object can change the notification of other objects without the other objects constantly polling for changes
When you need to buy something, all you have to do is pay attention to the retailer and do your own thing with your phone until it sends you a notification saying that the price has dropped. It doesn’t require you to open a shopping app every once in a while to see if the price is down. Which will save you time, reflected in the program, is that you don’t need every once in a while will go to the judge, is equivalent to set a timer, a while to judge whether meet the requirements, in turn, allows you to rely on the object to make corresponding action, send you a notice, it can significantly optimize the performance.
Advantages of the observer model?
-
As mentioned earlier, using the Observer mode at the right time can greatly optimize performance.
-
Two objects with strong data coupling can also be decoupled. For example, in order to judge whether a business has made an action, consumers have to poll judgment all the time, so each time they need to judge whether the business exists. However, in the observer mode, the observed does not need to know whether there is an observer, only needs to loop the list of observers to send the notification, and does not need to care whether the observer successfully receives the notification.
Disadvantages of the observer model?
- As a virtue, decoupling the two objects is not only its virtue, but also its weakness:
- Because the observed doesn’t care how many observers there are, they just send signals to each observer. Therefore, there is no way for the observed to receive feedback from the observer, and for those situations that require feedback, this model is no longer applicable
- The observed only knows that the observer has changed, but not how the observer has changed.
So how does the observer pattern work in real code?
Js class to show the observer mode in action:
class Subject {
constructor() {
this.observerList = [];
}
addObserver(observer) {
if(! observer.notify)return console.log('This is not an observer.');
this.observerList.push(observer);
}
deleteObserver(observer) {
let currentObserverIndex = this.observerList.indexOf(observer) currentObserverIndex ! = -1 ?
this.observerList.splice(currentObserverIndex, 1) : console.log('The observer does not exist')}notifyObservers() {
this.observerList.forEach(observer= > {
if(! observer.notify)console.log(observer + 'update failed, notify method does not exist'); observer.notify(); }}})class Observer {
constructor(name) {
this.name = name
}
notify() {
console.log('I am' + this.name + ', I updated it '); }}let observer1 = new Observer('Joe')
let observer2 = new Observer('bill')
let observer3 = new Observer('Cathy')
let subject1 = new Subject();
let subject2 = new Subject();
subject1.addObserver(observer1);
subject1.addObserver(observer2);
subject1.addObserver(observer3);
subject1.addObserver(subject2); // This is not an observer
subject1.notifyObservers(); // Invoke three updates
subject1.deleteObserver(observer2); // Delete observer observer2
subject1.deleteObserver(observer2); // Delete observer observer2 again
Copy the code
The above code will print
Let’s take a look at the code above
- First the observed needs to have an array
list
It’s used to store the observer, which is up hereobserverList
This array; - You also need a method to add observers to the array, which is the one above
addObserver
This method; - Finally, when the conditions are met, the observers are notified by a method of notifying observers, corresponding to the top
notifyObservers
This method.
These three are the most basic methods of an observed, including adding and deleting observers and modifying observer data
However, there should be a response method in the observer that responds when it receives a notification from the observed, such as notify
When writing the observer mode, note that the array can only be added to the observer object. You can check whether the notify method is present to determine whether the observer is present. Before deleting an observer, check whether the observer exists in the array. In summary, it is necessary to consider some possibility of data incoming or method use to avoid errors.
conclusion
Observer pattern is I learn first design patterns, in general the design train of thought was very interesting, can also solve the problem of part of the object between the notice, to treat a design pattern, it must be given its advantages for now a requirement to use, right to use the observer pattern, can bring great convenience for notification between objects.