“This is the first day of my participation in the Gwen Challenge in November. See details of the event: The last Gwen Challenge in 2021”.

The first public account of this article: Wukong chat framework link: click here

This is Wukong’s 121st original article

Hello everyone, I am Wukong.

The talk show convention is hot recently, I think everyone has seen it, so this time I will take you to see the observer mode of the convention.

1. Talk shows

The first is the role division of talk shows:

We think of a stand-up comedian as an Observable.

4 jokers + 180 audience members as observers.

What a comedian does: When a stand-up comedian is doing well, he flicks a light to show he’s very funny.

Audience duty: When a stand-up comedian is good, pick up the remote control and press the button to show that you like it.

This scenario is very much in line with the observer model, which is simply a group of observers observing and reacting to the object to be observed.

After the above examples, you must have a preliminary impression of the observer model.

Let’s take a look at what the observer pattern looks like in the world of programming.

Observer model

GoF design Pattern book says: define a one-to-many dependency between objects, when the state of one object changes, all dependent objects are automatically notified, this is the observer pattern.

The observer pattern has many other names, such as publish subscribe, listen callback, etc., but any scenario that fits the description above can be called the observer pattern.

The Java API has the observer mode built in, making it very easy to use. Usage: The java.util package contains the basic Observer interface and Observable class. In addition, data can be pushed or pulled between them.

Another important point: the relationship between the observed and the observer is one-to-many. In the example of the talk show above, there are many audiences and only one actor (or group of talk shows) at a time.

How does the observed work?

All you need to do is extend the Observable class. So let me walk you through what this Observable is made of.

Add observer

First of all, if we want to observe others, we need to be added as observers of others, so we need a method to add observers. Observale provides us with a method to add observers of others: addObserver.

Store observer

When there are a lot of people who want to be observers, don’t there have to be a place for them?

An Observable gives us a place to put all our observers: a Vector.

Remove observer

When we don’t want to be observed by someone, we just remove it.

Observable gives us a way to remove an observer: deleteObserver.

How does the observed give notice?

When the subject wants to tell the observer that his state has changed, does it have to send a notification?

Observable gives us two methods:

NotifyObservers () or notifyObservers(Object arg).

The difference is one with and one without. The no-parameter method is usually used when the observer pulls data.

As shown in the figure below, the observer is notified by push.

So what are the details of the notice?

In plain English, there are three steps:

  • The observed subjects first judge whether their state has changed.
  • Gets all added observers from the vector collection.
  • Loop over the observer, calling the observer’s UPDATE method.

Look at the source code more clearly, the comments are added.

public void notifyObservers(Object var1) { Object[] var2; Synchronized (this) {// When setChange() is called, this.changed = true if (! this.changed) { return; } // Get all observers var2 = this.obs.toarray (); // Reset the change state this.clearchanged (); } for(int var3 = var2. Length - 1; var3 >= 0; --var3) { ((Observer)var2[var3]).update(this, var1); }}Copy the code

Why setChanged?

Before being notified by the observer, the observed object calls the setChanged() method to indicate that the state has changed.

protected synchronized void clearChanged() {
  this.changed = false;
}
Copy the code

So why do I need to call this? Is it ok not to call?

When observers are called notifyObservers, they determine whether the state has changed, and if it has not, observers are not notified.

Advantage: More flexibility in notifying the observer. If you don’t want to constantly notify the observer, you can control the call to the setChanged method appropriately.

Others: You can also reset the changed state using clearChanged or get the changed state using the hasChanged method.

How does the observer work?

The Observer implements the Observer interface to become an Observer.

public interface Observer {
    void update(Observable var1, Object var2);
}
Copy the code

The observer then implements the update method, which is called on the observed object.

A brief episode about push and pull modes:

For push, call notifyObservers, transferring parameters to observers, or for pull, actively call the observed-get method, notifying observers, with or without parameters.

Five, code implementation

We define the comedian as Leader class, the audience as Viewer class, and the talk show Actor as Actor class.

The comedian is watching the actor perform a stand-up show and needs to be an observer of the actor. Just call actor.addobServer (leader).

The viewer is similarly called actor.addobServer (Viewer).

Based on the principle explained earlier, the presenter and audience must inherit the Observer interface and then implement the Update method.

Here’s what it looks like: When you receive a notification, react accordingly, such as flashing a light.

After each occurrence, the setChanged() method is called, along with notifyObservers, to notifyObservers, and updates for all observers are triggered.

Take a look at the actor notification code:

The execution result is as follows, Wang Mian’s performance is very wonderful, lead laughing member clap light!

Source code download, in the public number back: observer.

Okay, observer mode is interesting. How is it applied in e-commerce?

Six, about the design mode

Did you notice that there’s a little bit of a problem with how the observer and the observed work?

  • The observer needs to be added to a specific set of observed in order to observe, which is detail-oriented and violates the principle of abstraction oriented.
  • An Observable is a class, not an interface, and an Observable doesn’t implement an interface, which violates interface oriented programming.
  • An Observable must have a class that inherits Observable functionality. If a class has Observer functionality and wants to have functionality from another class, it becomes a dilemma because Java does not support multiple inheritance, limiting the reuse potential of an Observable.
  • In addition, the setChanged() method in the Observer API is protected (defined as protected), so you can’t create an Observable instance and combine it into your own object unless you inherit an Observable. It violates the principle of “more combination, less inheritance”.

7. Problems of architectural design

Problem 1: The above observer modes are all synchronous blocking, and the observed waits for the observer to complete the execution before executing the following code. How do you notify the observer asynchronously?

  • Scenario 1: Start a thread to call notifyObservers.
  • Scheme 2: Design idea of Google Guava EventBus framework

Question 2: How do I communicate across processes?

  • Scenario 1: We see that the observed calls the observer’s update method every time to notify the observer, so what do we do across processes? We can do this by calling the RPC interface synchronously.
  • Scenario 2: message queues, where multiple consumers and producers can subscribe to messages, similar to observers. However, the introduction of message queues increases maintenance costs.

Question 3: How do you communicate across machines?

  • Again, the message queue is introduced.

Viii. Application in e-commerce

Inventory can be used as an observer, goods receipt as an observer, when the inventory has changed, the need to generate a goods receipt, you can use the observer pattern, decouple goods receipt and goods inventory, if subsequent to generate other types of receipt and send a message to the administrator, directly add observer.

Nine, afterword.

This paper introduces the observer model through talk show convention, involving three roles: comedian, audience and talk show actor.

Then the working principle of the observer and the observed is explained in detail, and some questions related to design patterns are also discussed.

Then the problems introduced by the observer pattern are analyzed from the point of view of architecture design: synchronous invocation, cross-process communication, cross-machine communication.

Finally, it briefly describes the application scenarios of e-commerce, and hopes that you can leave a message to discuss.

Source code download, in the public number reply: observer.