Java Design Pattern----Observer pattern

Source: Internet
Author: User
Tags lenovo

Traditional MVC is believed to be used by everyone, especially the Web Developer (server side).

General data requests, changes will be the controller control, and then find the corresponding model, which is the general MVC. Then, once the model has changed, it can automatically feed back to the view, which is the Observer pattern ( an object changes, all objects that depend on it are notified and automatically updated ). (However, most MVC, such as the Struts2 of the presentation layer, does not seem to be implemented.) Why, its design mechanism or the BS model of the Web determines that it cannot be implemented. At least I found it that way when I was using it.


First look at an implementation of Android introduced by the original author, in fact, the author is also borrowed JAVA,JDK API, and then combined with the Android components to build a simple framework.


At the end of the article, I talk about the nature of observer.


This article reprinted from: http://blog.csdn.net/feiduclear_up/article/details/42167487

The Observer pattern "defines a one-to-many dependency between objects, and when an object's state changes, all objects that depend on it are notified and automatically updated", which can be understood as multiple observers subscribing to a message to the observer and notifying the appropriate observer to do their thing when the observer changes. The observer in ANDROID implements the Observer interface, and the observer inherits the observable class. Use the following steps:


1. The observer datawatcher implements the Observer interface.

2. The Observer datachange inherits the observable class.

3. The observer datawatcher to the observer DataChange to subscribe to the event (adding the Observer datawatcher to the DataChange of the person being observed).

4. The observed DataChange data changes, notify the observer datawathcer the corresponding data changes, please do the appropriate action.

5. The observer datawather to the observer DataChange to unsubscribe from the event (removing the observer datawatcher from the datachange of the observer).



The code is implemented as follows:

1. Observer class

Package com.example.observer;  Import java.util.Observable;    Import Java.util.Observer; /** * todo< Please describe what this class is for > * * @author XJP * @data: December 26, 2014 Morning 9:29:56 * @version: V1.0 */Public abstract C     Lass Datawatcher implements Observer {@Override public void update (Observable Observable, Object data) {} }

2. The class of the person being observed

package com.example.observer;    import java.util.observable;     /**  * TODO< Please describe what this class is for >  *   *  @author &NBSP;XJP   *  @data:  2014 December 26   Morning 9:30:21  *  @version:  v1.0  */   public class DataChange extends Observable {         private static DataChange instance = null;         public static datachange getinstance ()  {           if  (null == instance)  {               instance = new datachange ();           }           return instance;      }        public void  Notifydatachange (Data data)  {          // How does the observer inform the Observer that the data has changed?? Here are two ways to be critical.           setchanged ();           notifyobservers (data);       }    }

3. Operation class

Package com.example.observer;    import java.util.observable;  import  android.os.Bundle;  import android.app.Activity;  import android.util.Log;   import android.view.Menu;    public class MainActivity  extends activity {        private datawatcher  Watcher = new datawatcher ()  {              @Override           public void update ( Observable observable, object data)  {               super.update (Observable, data);               //observers receive notifications from the observer to update their data operations.               data mdata =  (Data) data;         &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;LOG.I ("Test",  "mdata---->>" +mdata.getdatachange ());           }        };          @Override       protected void  oncreate (bundle savedinstancestate)  {           super.oncreate (savedinstancestate);           Setcontentview (R.layout.activity_main);                               The  //simulates the observed data changes and updates the data.           data mdata = new data ();    &nBsp;      mdata.setdatachange (0);           datachange.getinstance (). Notifydatachange (Mdata);                 }                @Override       protected void onresume ()  {          super.onresume ();     The       //Observer adds a subscription event to the observed person.           datachange.getinstance (). AddObserver (watcher);       }            @ Override      protected void onpause ()  {           super.onpause ();           //observers removed from the observer queue            Datachange.getinstance (). Deleteobserver (Watcher);      }             }

4. Data class:

package com.example.observer;    /**  * todo< Please describe what this class is for >   *   *  @author  xjp  *  @data:  2014 December 26   9:33:33   *  @version: v1.0  */  public class data {         private int dataChange;         public data ()  {      }         public int getdatachange ()  {           return dataChange;      }         public void setdatachange (Int datachange)  {           this.dataChange = dataChange;      }     }

Note: I am mainly a framework for implementing the Observer Pattern code in Android, and how to write code depends on the actual business. In fact, the main idea of programming is the implementation of the framework.



My supplementary:

As seen above, the observer subscribed to the observer, but not every moment of monitoring & attention to be observed, if so, not only difficult to achieve, but also the cost of the system resources is very large (observers simply do not do things, every day to see the Observer is good hehe). In fact, one of the main points of the observer pattern is that although the observer is actively observing the subscription being observed, then the notice is taken by the observer to take the initiative. (Everything seems to be balanced again.)

A simple example:

Like said, my Lenovo computer is broken, I repair, and then the Shanghai side of the sale also learned that the matter, said that no engineers can arrange the door, staff recently lack of tight, then I can not always stare at their hands, every day to call the past to ask it? In fact, we all know that they have people, and then will come to ask me to make an appointment to repair the door. (The observed is Lenovo after-sales service, and then have the initiative to notify the right)


In general, I have summed up the core points of the authors above.

However, the author's point of view is still a little more obvious: The Observer may have more than one, its example is not reflected. (The Observer may notify multiple observers of the change), in fact, the observer pattern responds to a one-to-many relationship. an object changes, and then multiple objects that depend on it are notified and updated automatically.


Now that we know the principle, we're throwing away Java and Android components, for a more general (self-drawing implementation)

Well, I suddenly find that startuml himself has realized, you first look at it automatically generated diagram:

See, this is a kind of drawing (+subject means that the observer subscribes to the subject, here is the real line arrow, meaning direct contact. Subject here is the observer)

If I want to draw, I do not draw at all, I use the interface: (in his picture I change)


The observer, can be an organization, or it can be an individual (so I drew observer0,observer1 and so on)

The observer still relies on the change of the observer, and the dependency should begin at an abstraction level, so it is drawn on the interface.

However, the interface is generally not directly used, although interface-oriented programming, but the interface emphasizes the function, performance in the method, so generally will give him a default class (This is a lot of source code has done so, Android, struts, spring, all have to do), And put the observers together.


All right, Robbie, let's talk about it for half a minute.

My ability is limited, say so much, not too much, not too much.



Merlin

10/4/2015


Java Design Pattern----Observer pattern

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.