The author points Mr. Date: October 26, 2018

amway

Although I am just an app maker, many things in it are not very useful, but I mainly learn the habits of others. I have a lot of free time now. When I want to learn something, I am always disturbed by myself. Later, I used the tomato time mentioned inside, and I only need to refrain from looking at other things within the specified time, learning is still quite efficient. You can take a look at the rest of it.

First encounter the observer pattern

I can also how ah, is to learn about the observer mode, and then look at the source code, and then to learn rxjava1.0, and then look at 2.0, such a set of processes down, see is flowing, thinking is not stuck.

The observer pattern defines one-to-many dependencies between objects so that when an object changes state, all of its dependencies are notified and updated automatically.

We refer to multiple dependents as observers (subscribers/observers) and one dependent as a Subject (target /Subject)

Subscribing to a newspaper, I’m not going to do this example, too many people have done it, it’s boring. If you want to play, just play dirty, like… I don’t speak.

Publisher + subscriber = observer model

Whether it is the issue of subscribing to newspapers, or subscribing to something, as long as the model notifies the subscriber when the object changes state, it is called the observer mode. It doesn’t matter if each subscriber updates or doesn’t do anything, as long as the notification is in place.

Hand lift observer mode

To do this, let’s just clear our heads and see what we need to do.

  1. There is a Subject, and there is an Observer
  2. Subject needs to store all subscribed observers, so Subject has a collection of observers and add/remove methods
  3. Subject needs to notify all subscribing Observers to update data, so all observers have a method that can be invoked by Subject to update data
  4. B: No, we have met party A’s requirements. Open lu!!!!

Bridge bean sack !!!!!!!!!!!

Since all observers have at least one update method, we extract a parent class. And on the Subject side, let’s mention one. There may be more than one target in the program that needs to be monitored. I can be really a small clever son !!!! A picture illustrates the above.

Open masturbation !!!!

interface Subject {
    var observers: ArrayList<Observer>
        get() = ArrayList<Observer>()
        set(value) = TODO() fun registerObserver(observer: Observers) {// register observers. Add (Observer)} fun removeObserver(Observer: Observer) {// Delete observers. Remove (Observer)} funnotifyObservers() {/ / updatefor (observer inObservers) {observer.update(this)// notifying observers of updates}}}Copy the code
Interface Observer {fun update(subject: subject)}Copy the code

In a specific topic, we need to have a state change that causes all subscribers to be notified of the update.

class ConcreteSubject : Subject {
    private var subjectState: String? = null

    fun getState(): String? { 
        return subjectState
    }
    fun ChangeState(subjectState : String){
        this.subjectState = subjectState
        notifyObservers()
    }
}
Copy the code

In the case of specific observers, synchronization means receiving the message. In real development, just do what you want in update().


class ConcreteObserver : Observer {
    private var observerState: String? = null

    override fun update(subject: Subject) {
        observerState = (subject as ConcreteSubject).getState()
    }
}
Copy the code

When called by the client, register and then execute changeState() to change the observerState value of the currently registered object.

“Push” and “pull”

The observer mode can be divided into ** “push mode” and “pull mode” according to the different messages pushed. **

  1. Pull mode: In the demo written above, when we update data in the Subject class, observer.update(this). This passes the concreteSubject entity object. Because the concreteSubject object is acquired by the concreteObserver, we simply pull the data directly from the concreteSubject object when we need any information. The pattern in which a topic object directly transmits information to an observer is called a pull model
// Pull model observer.update(this)Copy the code
  1. Push mode: An object passed by the pull model, which contains a lot of information, and push mode, which is the specific information in the object, passed into. The mode in which the topic object conveys the specific information needed by the observer when it notifies the observer is called the push model.
Observer.update ((this as ConcreteSubject).getState())Copy the code

Note that the interface parameters are different when using the push model than when using the pull model.

  1. Security: Pull mode is a safer approach because only the specified information is provided to the subscriber. However, the push model is relatively insecure, because what the observer gets is an object that contains a lot of information, but it may not need so much information, and the extra information is a security risk. But when that happens, I recommend providing some get methods to get different data.

Java.util.Observer & Java.util.Observable

Java apis have built-in observer patterns, so why write them ourselves? That’s a good question! More on that later! Observer and Java.util.Observable correspond to Observer and Subject, respectively.

The first variable is the topic itself. The purpose of this update is to let the observer know which topic informs it. The second variable is the data object passed in notifyObservser().

Aye ~

  1. We just wrote the Subject as interface, and here we write the class.
  2. The ArrayList we use to store the Observer uses a Vector to store it.
  3. On add/remove Observer, it is written addObserver(), deleteObserver().
  4. It has notifyObservers() and notifyObservers(Object arg), which call the Observer update method.
  5. Added a Boolean attribute changed
  • Now to answer that question, why do we write an observer pattern ourselves? Java.util.Observable isn’t an interface, it’s a class. If you want to design a class that has the behavior of both an Observable and a superclass, there’s no way to do it. Java doesn’t support multiple inheritance. This limits Observable’s ability to reuse. Reuse is what motivates us to use design patterns!

  • About change Let’s look at some methods about change first.

Yeah, I see. These three methods simply change/get the value of change. Where is it used? This code is the only one called in this class, notifyObservers(Object ARG).

Oh !!!!!!!!!! I see. That is, if setChanged() is not called before notifyObservers(), observers will not be notified. What good is that? Flexible handling notification or not! The data may be updated every second, but the observer does not need to be updated so frequently and can call setChange() once in a while to retrieve the data.

Invert that. When using a built-in Observable, setChange() should be executed before notifying the observer!

And a couple of things

  • In the definition, we say that the observer pattern is a one-to-many dependency. One is the subject, which is mostly the observer, and the dependence is the one-way dependence of the observer on the subject. An observer cannot actively obtain information about a topic and must wait for the topic to be notified.
  • Topics notify observers of updates in an indeterminate order. The order in which multiple observers receive messages is uncertain, so don’t try to do anything here.
  • When a subscriber subscribes to more than one topic, there are generally two ways to deal with it in order to distinguish which topic is sending the message. 1. Subscribers have multiple update methods, and each topic invokes a different update method. 2. Update () determines which topic sent the message after receiving it (see java.util.observer).
  • The advantages of observer mode are as follows: abstract coupling between observer and target is realized; Dynamic linkage is realized;
  • Disadvantages of the observer mode: Since the topic is notified to all registered subscribers, if a certain piece of data does not need to be updated by a certain subscriber, the data may be mistakenly updated, which will cause trouble.

The last

The intention of writing this article is to learn about the observer model, but I still can’t think of a good topic (SAO), so I made a clickbait once. I don’t know whether UC will ask me to work. Starting next month, I won’t be writing about design patterns all the time. The company is late on salary, so even though it’s the end of the year, I need to learn something else to prepare for the interview. But if anyone likes my style of writing and rXJava-related stuff, I will write “Young Men Go to Such lengths to Learn RXJava! (2)”.

The following is my “design pattern series” article, welcome you to pay attention to the comments coin throw banana. You can also go into groups and discuss with the gods. Qq group: 557247785

Design Patterns introduction to Java and Kotlin’s singleton Pattern Kotlin’s Decorator Pattern and Source code Extensions From Shallow to Deep Understand the Factory Pattern in order to learn Rxjava, the young guy did this!