Android design mode scenario Analysis-Viewer mode

Source: Internet
Author: User

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:

public class MyObserver implements Observer { private String name; public MyObserver(String name) { this.name = name; } @Override public void update(Observable o, Object arg) { System.out.println(name + ", update:" + arg); }}

3. Write the test method:

@TestPublicvoidTest ()throws Exception {//by observer myobservable observable = new myobservable (); //observer myobserver observer1 = new myobserver (" test1 "); Myobserver observer2 = new myobserver ( "test2"); Myobserver Observer3 = new myobserver ( "test3"); Myobserver observer4 = new myobserver ( "test4"); //registers the Observer in the Observer List of the Observer object Observable.addobserver (OBSERVER1); Observable.addobserver (OBSERVER2); Observable.addobserver (OBSERVER3); Observable.addobserver (OBSERVER4); //release message observable.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:

PublicAbstractClassBaseadapterImplementsListAdapter,spinneradapter {//data set observer private Span class= "Hljs-keyword" >final datasetobservable mdatasetobservable = new Datasetobservable (); public void  Registerdatasetobserver (Datasetobserver observer) {MDATASETOBSERVABLE.REGISTEROBSERVER (Observer);} public void unregisterdatasetobserver ( Datasetobserver observer) {MDATASETOBSERVABLE.UNREGISTEROBSERVER (Observer);} //when the data set changes, notify all observers public void Span class= "Hljs-title" >notifydatasetchanged () {mdatasetobservable.notifychanged ();} //code omitted} 


/span>
We follow up to see the Mdatasetobservable.notifychanged () method:
public class datasetobservable extends observable<DataSetObserver> { Span class= "Hljs-comment" >//calls each observer's onChanged () method to notify them that the Observer has changed public void notifychanged () {synchronized (mObservers) {//Call All Observers onChanged () method for (1; I >= 0; i--) {Mobservers.get (i). On Changed (); }}} //code omitted}            

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:

PublicClassListviewExtendsAbslistview {Code omitted@OverridePublicvoidSetadapter (ListAdapter adapter) {If you already have a Adapter, then log out of the ADAPTER corresponding observerif (madapter! =Null && mdatasetobserver! =null) {madapter.unregisterdatasetobserver (mdatasetobserver);} //code omitted super.setadapter (adapter); if (madapter! = null) {mareallitemsselectable = Madapter.areallitemsenabled (); Molditemcount = Mitemcount; //get the number of data Mitemcount = Madapter.getcount (); Checkfocus (); //here Note: Create a data set observer Mdatasetobserver = new Adapterdatasetobserver (); //registered the Observer in Adapter, which was actually registered in Datasetobservable Madapter.registerdatasetobserver ( Mdatasetobserver); //code omitted} else {//Code omitted} requestlayout ();} //code omitted} 

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.