Android design mode scenario Analysis-Viewer mode

Source: Internet
Author: User

Reprint Please specify source: http://blog.csdn.net/smartbetter/article/details/70755775

The Observer pattern is a very high frequency mode, sometimes referred to as the Publish/subscribe mode, is a behavioral pattern, it is most commonly used in the GUI system, subscription-publishing system, it is an important role of decoupling, making them less dependent. The Observer pattern defines a one-to-many dependency between objects, so that whenever an object changes state, all objects that depend on it are notified and automatically updated.

1. Usage Scenarios for observer patterns

Correlated behavior scenarios, event-level triggering scenarios, cross-system message exchange scenarios such as Message Queuing, event bus processing mechanisms.

2. Advantages and disadvantages of using observer patterns in programs
- Observer Pattern
Advantages There is a coupling abstraction between the observer and the Observer, responding to business changes, and enhancing system flexibility and scalability.
Disadvantages Development debugging is more complicated, the notification of messages in Java is sequential execution, and the lag of a message affects the overall efficiency of execution, so the use of observer patterns also requires a combination of asynchronous operations.
3. UML class diagram of the Observer pattern

Subject: Abstract subject, observed (Observable) role, ConcreteSubject: specific subject; Observer: abstract observer; Concreteobserver: specific observer.

4. Implementation of the Observer pattern

The observer Observer and the Observer Observable are built-in types in the JDK.

1. Create the viewer:

publicclass MyObserver implements Observer {    private String name;    publicMyObserver(String name) {        this.name = name;    }    @Override    publicvoidupdate(Observable o, Object arg) {        ", update:" + arg);    }}

2. Create the observed person:

publicclass MyObservable extends Observable {    publicvoidpostNewPublication(String content) {        // 标识状态或者内容发生改变        setChanged();        // 通知所有观察者        notifyObservers(content);    }}

3. Write the test method:

@Test Public void Test()throwsException {//The person being observedMyobservable observable =NewMyobservable ();//ObserverMyobserver Observer1 =NewMyobserver ("Test1"); Myobserver Observer2 =NewMyobserver ("Test2"); Myobserver Observer3 =NewMyobserver ("Test3"); Myobserver observer4 =NewMyobserver ("Test4");//Register the Observer in the Observer list of the object being observedObservable.addobserver (Observer1);    Observable.addobserver (OBSERVER2);    Observable.addobserver (OBSERVER3); Observable.addobserver (OBSERVER4);//Post a messageObservable.postnewpublication ("New");}

Output Result:

test4, update:newtest3, update:newtest2, update:newtest1, update:new

You can see that all observers subscribed to the observer have received the update message, and a one-to-many subscription-publishing system is complete.

Application scenarios in 5.Android system source code 1.notifyDataSetChanged () method

After we have added data using the ListView, we call Adapter's Notifydatasetchanged () method to dynamically update the data.

The Notifydatasetchanged () method is defined in Baseadapter, and Baseadapter is an observer pattern:

 Public Abstract  class baseadapter implements listadapter, spinneradapter {    //Data Set Viewer    Private FinalDatasetobservable mdatasetobservable =NewDatasetobservable (); Public void Registerdatasetobserver(Datasetobserver observer)    {MDATASETOBSERVABLE.REGISTEROBSERVER (Observer); } Public void Unregisterdatasetobserver(Datasetobserver observer)    {MDATASETOBSERVABLE.UNREGISTEROBSERVER (Observer); }notify all observers when data set changes     Public void notifydatasetchanged() {mdatasetobservable.notifychanged (); }//Code omission}

We follow up to see the Mdatasetobservable.notifychanged () method:

 Public  class datasetobservable extends Observable<datasetobserver > {    //Call each observer's onChanged () method to notify them that the Observer has changed     Public void notifychanged() {synchronized(mobservers) {//Call all Observer's onChanged () method             for(inti = mobservers.size ()-1; I >=0;            i--) {mobservers.get (i). onChanged (); }        }    }//Code omission}

This code is to walk all the observers in mdatasetobservable.notifychanged () and invoke their onChanged () method to tell the observer that something has changed.

So where do these observers come from? In fact, the ListView is generated by setting Adapter with the Setadapter () method, let's take a look at the relevant code:

 Public  class ListView extends abslistview {    //Code omission    @Override     Public void Setadapter(ListAdapter adapter) {//If you already have a Adapter, log out of the ADAPTER corresponding observer first        if(Madapter! =NULL&& Mdatasetobserver! =NULL) {madapter.unregisterdatasetobserver (mdatasetobserver); }//Code omission        Super. Setadapter (adapter);if(Madapter! =NULL) {mareallitemsselectable = madapter.areallitemsenabled (); Molditemcount = Mitemcount;//Get the number of dataMitemcount = Madapter.getcount (); Checkfocus ();//Note here: Create a data set observerMdatasetobserver =NewAdapterdatasetobserver ();//Register this observer with Adapter and actually register it in datasetobservableMadapter.registerdatasetobserver (Mdatasetobserver);//Code omission}Else{//Code omission} requestlayout (); }//Code omission}

As we can see, when setting up Adapter, a adapterdatasetobserver is constructed, that is, the observer, and finally, the Observer is registered to Adapter.

Here we know that when the data of the ListView changes, call Adapter's Notifydatasetchanged () method, which again calls the Datasetobservable notifychanged () method, This method calls the OnChanged () method of all observers (Adapterdatasetobserver), and in the OnChanged () method calls the ListView re-layout method so that the ListView refreshes the interface, which is an observer pattern.

Android design mode scenario Analysis-Viewer mode

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.