Java _ observer mode (observable and observer)

Source: Internet
Author: User
1. Introduction to observer Mode

In Java, the observer mode is implemented through the observable class and the observer interface. An observer object monitors the changes of an observable object. When the observable object changes, the observer will be notified to perform relevant work.

If image A shows the data in the database, and image B modifies the data in the database, then image a will load it again. In this case, the observer mode can be used.

Ii. Observer mode Implementation Method

Java. util. observable has two methods that are particularly important to observer.

① Setchanged () method

    /**     * Sets the changed flag for this {@code Observable}. After calling     * {@code setChanged()}, {@code hasChanged()} will return {@code true}.     */    protected void setChanged() {        changed = true;    }

② Yyobservers () method/notifyobservers (Object Data) Method

    /**     * If {@code hasChanged()} returns {@code true}, calls the {@code update()}     * method for every observer in the list of observers using null as the     * argument. Afterwards, calls {@code clearChanged()}.     * <p>     * Equivalent to calling {@code notifyObservers(null)}.     */    public void notifyObservers() {        notifyObservers(null);    }    /**     * If {@code hasChanged()} returns {@code true}, calls the {@code update()}     * method for every Observer in the list of observers using the specified     * argument. Afterwards calls {@code clearChanged()}.     *     * @param data     *            the argument passed to {@code update()}.     */    @SuppressWarnings("unchecked")    public void notifyObservers(Object data) {        int size = 0;        Observer[] arrays = null;        synchronized (this) {            if (hasChanged()) {                clearChanged();                size = observers.size();                arrays = new Observer[size];                observers.toArray(arrays);            }        }        if (arrays != null) {            for (Observer observer : arrays) {                observer.update(this, data);            }        }    }

The above two methods are very important.

Setchanged () method
--

Used to set an internal flag indicating that the data has changed

Yyobservers () method
/Yyobservers (Object Data) Method --

When all the observer data changes, all the observer will automatically call the rewritten Update (observable
Observable, object data) method for some processing (such as screen data update ).

We can see that there are two methods to notify the observer: one with no parameters and the other with parameters. So what is the role of this parameter?

One function: Now I don't want to notify all the observers, but only want one of them to do some processing, so I can pass a parameter as the ID and then judge it in all the observers, each Observer determines that some processing is performed only when the received parameter ID is its own.

Of course, the parameter has other functions. I just gave an example.

The following is an example:

Import Java. util. observable;/*** observable class */public class simpleobservable extends observable {private int DATA = 0; Public int getdata () {return data;} public void setdata (int I) {If (this. data! = I) {This. data = I; setchanged (); // only after setchange () is called, yyobservers () will call Update (); otherwise, nothing will be done. Yyobservers ();}}}

The above class is an observer class, which inherits the observable class, indicating that this class can be observed.

Then, in the setdata () method, where the data changes, call the setchanged () and notifyobservers () Methods of the observable class, indicates that the data has changed and all observers are notified to call their update () method for some processing.

Note: notifyobservers () will call Update () only after setchange () is called. Otherwise, nothing will be done.

/*** Observer class */public class simpleobserver implements observer {public simpleobserver (simpleobservable) {simpleobservable. addobserver (this);} public void Update (observable, object data) {// data is an arbitrary object, used to pass the system parameter. out. println ("data has changed to" + (simpleobservable) observable. getdata ());}}

By generating an instance of the simpleobservable class, you can call the addobserver (this) method to make The Observer (simpleobserver class) observe the simpleobservable class.

Then we need to rewrite the update () method to process the changed data.

Below we can write a simple test class to test it.

public class SimpleTest  {     public static void main(String[] args){        SimpleObservable doc = new SimpleObservable ();        SimpleObserver view = new SimpleObserver (doc);        doc.setData(1);        doc.setData(2);        doc.setData(2);        doc.setData(3);      }  } 

The running result is as follows:

Data has changed to 1 data has changed to 2 // The second time setdata (2), because there is no setchange, the update is not called data has changed to 3

The following describes some other attributes and methods of an observable class.

Property --

// Observers is a list that stores all the observers to be notified. List <observer> Observers = new arraylist <observer> (); // changed is a Boolean flag, indicating whether the data has changed. Boolean changed = false;

Method --

// Add an observer to the public void addobserver (Observer observer) {If (Observer = NULL) {Throw new nullpointerexception ();} synchronized (this) {If (! Observers. contains (observer) observers. add (observer) ;}}// delete an observerpublic synchronized void deleteobserver (Observer observer) {observers. remove (observer);} // clear the observerspublic synchronized void deleteobservers () {observers. clear ();} // returns the number of observers in the observers list. Public int countobservers () {return observers. size ();} // reset the Data Change flag to protected void clearchanged () {changed = false;} // Change the data flag to protected void setchanged () {changed = true;} // judge the value of the Flag public Boolean haschanged () {return changed ;} // notify all observers (without parameters) Public void policyobservers () {policyobservers (null) ;}// notify all observers (with parameters) @ suppresswarnings ("unchecked ") public void policyobservers (Object Data) {int size = 0; Observer [] arrays = NULL; synchronized (this) {If (haschanged () {clearchanged (); size = observers. Size (); arrays = new observer [size]; observers. toarray (arrays) ;}} if (arrays! = NULL) {for (Observer observer: arrays) {observer. Update (this, data );}}}

Note: Before the observer object is destroyed, use deleteobserver to delete it from the list, that is, call the deleteobserver () method in the ondestroy () method.

Otherwise, the observer object will not be garbage collected, causing memory leakage, and the dead observer will still be notified, which may cause unexpected errors, as the list grows, the yyobservers operation slows down.

The following two projects are the classic application of observable and observer. They are a single-finger drag-and-zoom operation implemented by Android.

Two examples:

Http://download.csdn.net/detail/tianjf0514/4237628

Http://download.csdn.net/download/tianjf0514/4237634

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.