I recently wanted to delve into responsive programming, and as a foundation it was necessary to polish the observer mode; I thought it was easy at first, and then I just started masturbating, and I found that it didn't work. Because all of a sudden I don't understand the model, the observer, which of the publish-subscribe executors is the observer? Or are there other characters? But according to the structure in The book JAVA and Patterns, no additional characters appear.

Think of… , well can’t think of…. Run to…

When I run, I give myself a list of questions:

GOF defines the observer pattern as follows: defines a one-to-many dependency between objects. When an object’s state changes, all dependent objects are notified and automatically updated.

  • Since it is the object state that has changed, whose state has changed and who has been notified.
  • The observer model can also be called “publish-subscribe”, so whether the observer takes on the role of “publish” or “subscribe”. Is the observer active or passive?
  • What did the observed do? Is it an active or passive role?

Here due to some stereotyped thinking, there is always a feeling that since it is “observed”, does the word “observed” mean that “observed” is the party passively receiving changes, that is, the party receiving notification?

Before I also walked to this alley, program write always feel where wrong; Looking back, or their own too young, did not get what big guys point.

Let’s start with the program; To use the Nuggets as an analogy, my blog glmmaper is the observed, the publisher. The nuggets act as observers, aka subscribers.

My friends (subscribers) follow (subscribe) my blog (publisher), if I post an article (status change), I will notify (push message) all my friends who follow me.

package com.glmapper.designmode.observor;
/ * * *@descriptionAbstract topic interface *@email: <a href="[email protected]"></a>
 * @author: lei uncle *@date: 18/4/22 * /
public interface Subject {
    /** * New follower *@param*/
    void addFocusObserver(Observer observer);

    /** * unsubscribe *@paramObserver unfollows partners */
    void removeFocusObserver(Observer observer);

    /** * Notification mechanism. Notification mechanism is triggered by related events, such as post *@paramBlogName Name of a blog@paramArticleName Name of the article */
    void notifyObservers(String blogName,String articleName);
}
Copy the code

Three methods: one is to add a follower to the homepage of the blog; One is the unfollowing of a blog’s homepage by a friend. Obviously you unfollow, why say I remove you, that is, do not let you follow, still can play like this? There must be some other support mechanism to be introduced, such as when you make an unfollow request on the client and the nuggets engineers remove you from my watch list while processing it on the back end. 😄…). ; The final method is to initiate a notification. Here’s a specific blog, glmapper;

package com.glmapper.designmode.observor;

import java.util.ArrayList;
import java.util.List;

/ * * *@description: This is the specific publisher of my blog glmapper *@email: <a href="[email protected]"></a>
 * @author: lei uncle *@date: 18/4/22 * /
public class ConcreteSubject implements  Subject {
    /** My current concern list */
    List<Observer> Observers = new ArrayList<>();
    /** My blog name: */
    private static final String blogName = "glmapper";

    @Override
    public void addFocusObserver(Observer observer) {
        Observers.add(observer);
    }

    @Override
    public void removeFocusObserver(Observer observer) {
        Observers.remove(observer);
    }

    @Override
    public void notifyObservers(String blogName,String articleName) {
        for(Observer observer:Observers) { observer.update(blogName,articleName); }}/** ** */
    public void publishArticle(String articleName){ notifyObservers(blogName,articleName); }}Copy the code

As mentioned above, the notification event must be due to some status change, for example, I published a blog, and then notify you (here only if you pay attention). And the observer:

package com.glmapper.designmode.observor;

/ * * *@description: Subscriber Abstract interface *@email: <a href="[email protected]"></a>
 * @author: lei uncle *@date: 18/4/22 * /
public interface Observer {
    /** * Calling this method updates the status and takes the appropriate action *@param blogName
     * @param articleName
     */
    void update(String blogName,String articleName);
}
Copy the code

The abstract subscriber has an update method that tells you to take the corresponding action, which may vary from observer to observer.

package com.glmapper.designmode.observor;

/ * * *@description: This is the specific subscribers, which can be likened to blog followers, * after receiving the change of information, they need to take corresponding actions *@email: <a href="[email protected]"></a>
 * @author: lei uncle *@date: 18/4/22 * /
public class ConcreteObserver implements Observer {

    @Override
    public void update(String blogName,String articleName) {
        System.out.println(blogName+"Published a new article called:"+articleName);
        read(articleName);
    }

    private void read(String articleName){
        System.out.println("Coming to read"+articleName+"This article"); }}Copy the code

Above is a specific follower, join say is you. A blog update sends you a notification (from the Nuggets app) and you click on it, which is also an action. An example of this is read, where the follower acts to read.

Take a look at the final result:

package com.glmapper.designmode.observor;

/ * * *@description: [Description text] *@email: <a href="[email protected]"></a>
 * @author: lei uncle *@date: 18/4/22 * /
public class MyMainIndex{

    public static void main(String[] args) {
        // The blog body
        ConcreteSubject subject = new ConcreteSubject();
        // Followers: handSome means handSome
        Observer handSome = new ConcreteObserver();
        // Add a follower
        subject.addFocusObserver(handSome);
        // Post an article
        subject.publishArticle("Design Pattern-Observer Pattern"); Glmapper has published a new article called design Patterns-Observer PatternsCopy the code

The barrel said: Ah, happy hour is always short

So as accumulation, or need to list a few basic concepts.

Main roles:

  • Abstract Topic roles (Subject: A topic role stores all references to observer objects in a collection, and each topic can have any number of observers. Abstract topics provide interfaces for adding and deleting observer objects.
  • Abstract Observer Role (Observer) : Defines an interface for all concrete observers to update themselves when the subject being observed changes.
  • ConcreteSubject (1) : Stores state to a ConcreteSubject, notifying all registered observers when the internal state of a ConcreteSubject changes. A concrete topic role is usually implemented with a concrete subclass.
  • ConcretedObserver: Stores a concrete topic object, stores the associated state, and implements the update interface required by the abstract observer role to match its state to the topic’s state.

Specific relationship:

  • Abstract topic (interface)–> Implemented by ConcreteSubject role (1)

  • Abstract Observer –> Implemented by ConcretedObserver role (N)

  • The observer object loads the topic method and calls update, the interface method implemented by the observer object, in the topic method to make itself change in response.

Some scenarios:

  • When changes to one object cause changes to other objects, you can’t predict how many objects will need to be changed.
  • When an object needs to have the ability to notify other objects without knowing what type those objects are.

There are many specific implementation examples based on publishing and subscription. The typical one is this kind of subscription to a blog, and then the blog updates push. There are also wechat public account, service account and so on.

Let’s go back to the questions we left at the beginning:

  • The observed state changes and then “actively notifies” the observer, not that the observer actively seeks notification.
  • The observed is the message publisher and the observer is the message subscriber. The observer is the passive receiver.
  • The role of the observed is to store the current list of observers, and then provide some notification mechanism to tell the observer that the state has changed and that he is the actor.

OK, the observer mode is here, also welcome friends to put forward their precious opinions; If there is any improper writing, please put forward in time.

Broadcast: rookie growth series began to update....