Java support for observer patterns

Source: Internet
Author: User

In the Java language Java.util Library, a observable class and a observer interface are provided, which form the Java language support for the Observer pattern.

The following is a direct look at how to use Java for observer mode support:

In the following example, the object of the observer is called watched, which is monitored, while the Observer object is called Watcher, which is the meaning of the watcher.

The watched object inherits from the observable class, and the Watcher object implements the Observer interface.

/** * is monitored object */public class watched extends observable{    private String data= "";    /* * Value Method    * *    /public String retrievedata ()    {        return data;    }    /* * Change Method * * */public    void Changedata (String data)    {        if (!this.data.equals (data))        {            This.data=data;            Setchanged ();        }        Notifyobservers ();    }

/** * Monitors */public class Watcher implements observer{public    watcher (watched W)    {        w.addobserver (this);    }    @Override public    void update (Observable o, Object Arg) {        System.out.println ("Data have been changed to: '" + (( Watched) O). Retrievedata () + "'");    }}

public class tester{    private static watched watched;    private static Observer watcher;    public static void Main (string[] args) {        watched=new watched ();        Watcher=new Watcher (watched);        Watched.changedata ("1");        Watched.changedata ("1");        Watched.changedata ("2");        Watched.changedata ("3");}    }

Java support for observer patterns

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.