In the daily development process often need to use design patterns, but there are 23 design patterns, how to make these design patterns clear and can be applied in the actual development process smoothly? With me to follow the “Android source code design pattern analysis and actual combat” book learning while application!

Design Patterns series of articles

  • Six principles of Object Orientation in Android design Pattern
  • Android design pattern singleton pattern
  • Android Design Mode Builder mode
  • Android design pattern factory method pattern
  • Android Design Pattern observer mode
  • Proxy for Android design patterns
  • Android Design Mode decorator mode

Today we’re going to talk about the observer model


define

Define a one-to-many dependency between objects so that whenever an object changes state, all dependent objects are notified and automatically updated.

Usage scenarios

  • Associated behavior scenario
  • Multi-level event triggering scenario
  • Cross-system information exchange scenarios, such as message queues, event bus processing mechanisms

Using the example

  • A common publish-subscribe model
  • The notifyDataSetChanged update method of the ListView Adapter
  • BroadcastReceiver
  • Open source library EventBus
  • RxJava

implementation

The four roles

  • Abstract themes, also known as observables, store references to all observer objects in a collection. Each theme can have any number of observers. Abstract themes provide interfaces to add and remove observer objects
  • A concrete topic (concrete observed), which is a subclass of abstract topics, stores the relevant state in the concrete observer object and notifies all registered observers of changes in the state within the concrete topic
  • The abstract observer, the abstract class of the observer, defines an updated interface
  • The concrete observer realizes the update interface of the abstract observer, and updates its own state when the observed state changes

Key points of implementation

  • The key point is to grasp the above four roles
  • Design pattern is an idea that can be realized according to specific needs in the application process. Both RxJava and ListView adapters use the observer mode, but the implementation is bound to be different

implementation

Observable class and Observer interface in JDK

  • The JDK has Observable and Observer interfaces
  • The Observer implements the Observer interface and the observed inherits the Observable class
  • The observed adds an observer through the addObserver method of the Observable class

The observer

public class MyObserver implements Observer{
    private String mName;

    public MyObserver(String name) {
        mName = name;
    }

    @Override
    public void update(Observable o, Object arg) {
        System.out.println(mName + "-- >" + "update: "+ arg); }}Copy the code
  • The Observer interface consists of an Update method, Observable, and Object, which represents what is being updated by the Observer

The observed

Public class MyObservable extends Observable{public void sendChangeMeg(String Content) {// This method inherits from an Observable to indicate changes in status or contentsetChanged(); // The method extends to Observable, notifying all observers, and finally calling notifyObservers(content), an update method for each Observer. }}Copy the code
  • Observers signal the changes with setChanged(), and notify all observers with notifyObservers
  • NotifyObservers iterate over all observers and call their update method
  • The parameter in notifyObservers is the Object ARg, the last parameter passed to the observer update method

test

public class ObserverPatternTest {
    @Test
    public void test1() throws Exception {
        MyObservable myObservable = new MyObservable();

        MyObserver myObserver1 = new MyObserver("observer-1");
        MyObserver myObserver2 = new MyObserver("observer-2"); myObservable.addObserver(myObserver1); myObservable.addObserver(myObserver2); / / release the myObservable. SendChangeMeg ("Update released."); }}Copy the code

The test results

  • Don’t know what did you see the above test results, the observant friend may find that when the order is myObserver1, we add the observer myObserver2, but the result output is first myObserver2 myObserver1 again, why?

Look at the source code

The source code of observables
public class Observable {
    private boolean changed = false;
    private final ArrayList<Observer> observers;

    /** Construct an Observable with zero Observers. */

    public Observable() {
        observers = new ArrayList<>();
    }
    
    public synchronized void addObserver(Observer o) {
        if (o == null)
            throw new NullPointerException();
        if(! observers.contains(o)) { observers.add(o); } } public synchronized void deleteObserver(Observer o) { observers.remove(o); } public voidnotifyObservers() {
        notifyObservers(null);
    }
  
    public void notifyObservers(Object arg) {
        /*
         * a temporary array buffer, used as a snapshot of the state of
         * current Observers.
         */
        Observer[] arrLocal;

        synchronized (this) {
            if(! hasChanged())return; arrLocal = observers.toArray(new Observer[observers.size()]); clearChanged(); } // Notice the starting point herefor (int i = arrLocal.length-1; i>=0; i--)
            arrLocal[i].update(this, arg);
    }

    public synchronized void deleteObservers() {
        observers.clear();
    }

    protected synchronized void setChanged() {
        changed = true;
    }

    protected synchronized void clearChanged() {
        changed = false;
    }

    public synchronized boolean hasChanged() {
        return changed;
    }

    public synchronized int countObservers() {
        returnobservers.size(); }}Copy the code
  • First, when an Observable is generated, an ArrayList is initialized to hold all Observer observers
  • When we call notifyObservers, they are repeated over all the added observers, starting with the last Observer, and the update method of observers is called, as in the picture we tested above
  • The key to decoupling is that an Observer is an interface, and our observers all implement that interface
public interface Observer {
    void update(Observable o, Object arg);
}
Copy the code
  • What are the design principles behind this? If you forget the six principles we learned earlier, you can review them.
Other implementation methods, such as ListView Adapter and RxJava inside the observer mode, you can also try to look at the source, find the observer mode in the four roles

conclusion

  • Observer mode is a highly used mode. One of its important functions is to decouple the observer from the observer
  • Common places are GUI systems, publish-subscribe systems
  • Applying the observer pattern requires consideration of both development efficiency and operational efficiency

Welcome to pay attention to my wechat public number, looking forward to learning, communicating and growing together with you!