Observer model
When a subject’s state changes, other registered objects can observe the change and make their own changes accordingly. In this way to reduce dependency,
\
\
\
Here’s an example:
Take wechat moments for example.
You are the Subject and your friend is the Observer. When you send notify, all your friends can see it, and they like it and update it.
\
Subject
We abstract the “you” out, and that’s it:
You can add and remove observers by attaching and detach.
\
And then through the concrete “you”, to implement these methods.
\
Observer
Now let’s abstract out the “friends”
Then through the specific “friends”, can carry out some operations such as likes, comments.
\
test
As you can see, the subscription is maintained through concreteSubject, and after notifyObserver is used to notify the subscriber, the observer gets the information and processes it accordingly (see likes or comments).
Their relationship can be shown below:
Each observer just needs to deal with its own logic.
If new business is added, simply implement the Observer and maintain it in the observers container. Decoupling.