Android and design pattern-Observer (Observer) Pattern

Source: Internet
Author: User

Android and design pattern-Observer (Observer) Pattern
Dr. Yan macro's book "JAVA and patterns" describes the Observer (Observer) mode in this way:

  The observer mode is the behavior mode of an object. It is also called the Publish/Subscribe mode, Model-View mode, and Source-Listener (Source/Listener) mode) mode or Dependents mode.
The observer mode defines a one-to-many dependency, allowing multiple observer objects to listen to a topic object at the same time. When the status of this topic object changes, it notifies all observer objects so that they can automatically update themselves.


Structure of observer Mode
A software system contains various objects, just as a thriving forest is filled with various creatures. In a forest, various creatures depend on and constrain each other to form a biological chain. Changes in the state of a creature can lead to the corresponding actions of other creatures, and each creature is in the interaction of other creatures.

Similarly, a software system often requires that some other objects change accordingly when the state of an object changes. There are many design solutions to achieve this, but in order to make the system easy to reuse, we should choose a low coupling design. Reducing the coupling between objects is conducive to the reuse of the system, but at the same time, the designer needs to make the objects with low Coupling Degree consistent with each other to ensure high collaboration. The observer pattern is the most important in various design schemes that meet this requirement. (From the network)



It is the basic model of the observer mode. Taking the call state as an example, we can analyze how this event is transmitted when the call status of a mobile phone changes.

RegistrantList is the notifier. Registrant is the observer. RegistrantList provides add, remove, and policyregistrants to manage Registrant.

1. How is the call status monitored?

MCallStateRegistrants is an object of RegistrantList. It is generated in BaseCommand. java and encapsulates the addition and deletion of RegistrantList notifiers:

protected RegistrantList mCallStateRegistrants = new RegistrantList();

Public void registerForCallStateChanged (Handler h, int what, Object obj) {Registrant r = new Registrant (h, what, obj); // observer mCallStateRegistrants. add (r);} public void unregisterForCallStateChanged (Handler h) {mCallStateRegistrants. remove (h );}

In registerForCallStateChanged, a Registrant observer is added to the notifiers. How does Registrant store it?

    public synchronized void    add(Registrant r)    {        removeCleared();        registrants.add(r);    }
Registrants is an ArrayList object. Managing Registrant is actually an operation on ArrayList.

RegisterForCallStateChanged is called in the GsmCallTracker. java constructor:

mCi.registerForCallStateChanged(this, EVENT_CALL_STATE_CHANGE, null);
This is GsmCallTracker. GsmCallTracker inherits Handler. In this case, GsmCallTracker becomes the observer. When CallState changes, mCallStateRegistrants should notify GsmCallTracker.
You can log out without listening:

mCi.unregisterForCallStateChanged(this);


2. How does mCallStateRegistrants notify GsmCallTracker that the CallState has changed?
In the mobile phone, when the call status changes, the Modem will send a message up and pass it to the framework, which is received and processed by RIL. java:

            case RIL_UNSOL_RESPONSE_CALL_STATE_CHANGED:                if (RILJ_LOGD) unsljLog(response);                mCallStateRegistrants                    .notifyRegistrants(new AsyncResult(null, null, null));            break;

MCallStateRegistrants uses policyregistrants to notify all its observers:

    public /*synchronized*/ void    notifyResult(Object result)    {        internalNotifyRegistrants (result, null);    }    private synchronized void    internalNotifyRegistrants (Object result, Throwable exception)    {       for (int i = 0, s = registrants.size(); i < s ; i++) {            Registrant  r = (Registrant) registrants.get(i);            r.internalNotifyRegistrant(result, exception);       }    }

Registrants is the ArrayList, traversal, and notification of all the previously stored observers.

3. How does the observer Registrant respond to notifications?

The above shows r. internalpolicyregistrant (result, exception). The observer knows who will actually handle the callstate change?

Registrant code:

    internalNotifyRegistrant (Object result, Throwable exception)    {        Handler h = getHandler();        if (h == null) {            clear();            /// M: Registrant Debug Log Enhancement            Log.d("Registrant", "internalNotifyRegistrant(): Warning! Handler is null, it could be already GCed. ( what=" + what + ", userObj=" + userObj + ", result=" + result + ", exception=" + exception + " )");        } else {            Message msg = Message.obtain();            msg.what = what;                        msg.obj = new AsyncResult(userObj, result, exception);                        h.sendMessage(msg);        }    }
Handler h = getHandler (); The obtained Handler is the this mentioned above, that is, GsmCallTracker. what is the second parameter EVENT_CALL_STATE_CHANGE during registerForCallStateChanged registration. Here h. sendMessage is the message sent by the Handler GsmCallTracker. As we all know, all messages sent by Handler are received and processed by its own handleMessage () method.

Therefore, we can see in the GsmCallTracker handleMessage () method:

            case EVENT_CALL_STATE_CHANGE:                pollCallsWhenSafe();            break;
We don't care what we do...

Android Telephony uses a large number of observer modes in the source code to help us read the source code.

Not yet resumed. please correct me if there is anything wrong.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.