The observer pattern in Java internal implementation

Source: Internet
Author: User

If the admin wants to observe user's salary change, when the user's salary increases or decreases, will cause the admin to output the corresponding information.

Defining the Observer Interface: Myobserver.java

 Package Cn.liuning.watch;  Public Interface myobserver {    void  update (myobservable o, Object arg);}
View Code

Define the observed parent class (the Admin class needs to inherit this class): Myobservable.java

 PackageCn.liuning.watch;ImportJava.util.Observer;ImportJava.util.Vector;/*** Viewer mode, Java source code *@authorliuning **/ Public classmyobservable {/*** Mark whether to be observed this change*/    Private BooleanChanged =false; /*** Save all the observers*/    PrivateVector<myobserver>All ; /*** Viewer Constructor*/     Publicmyobservable () { all=NewVector<myobserver>(); }        /*** Add a viewer *@paramo*/     Public synchronized voidaddobserver (Myobserver o) {if(O = =NULL){            Throw NewNullPointerException (); }        if(!all.contains (o))        {all.addelement (o); }    }        /*** Delete an observer *@paramo*/     Public synchronized voiddeleteobserver (Observer o) {all.removeelement (o); }        /*** Be observed this informs the observer to make corresponding changes*/     Public voidnotifyobservers () {notifyobservers (NULL); }        /*** Be observed this informs the observer to make corresponding changes*/     Public voidnotifyobservers (Object Arg) {object[] arrlocal; synchronized( This) {            if(!changed) {                return ; } arrlocal=All.toarray ();        Clearchanged (); }         for(inti = arrlocal.length-1; i>=0; i--) {((myobserver) arrlocal[i]). Update ( This, ARG); }     }        /*** Delete all observers*/      Public synchronized voiddeleteobservers () {all.removeallelements (); }          /*** Settings are observed this changes*/     protected synchronized voidsetchanged () {changed=true; }          /*** Clear Changes*/     protected synchronized voidclearchanged () {changed=false; }          /*** Determine if there is a change *@returnBoolean*/      Public synchronized BooleanhasChanged () {returnchanged; }          /*** Count, get the number of observers *@return      */      Public synchronized intcountobservers () {returnall.size (); }    }
View Code

Define observer (need to implement Myobservable interface): Admin.java

 Package Cn.liuning.watch;  Public class Implements myobserver{    @Override    publicvoid  update (myobservable o, Object Arg) {                = (User) o;                System.out.println (Arg+ "money changed");                System.out.println (User.tostring ());    }    }
View Code

Define the Observer (need to inherit Myobserver): User.java

 PackageCn.liuning.watch; Public classUserextendsmyobservable{Private intPrice = 0; PrivateString name = "Zhang San";  PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     Public intGetPrice () {returnPrice ; } @Override PublicString toString () {return"User [price=" + Price + ", name=" + name + "]"; }     Public voidSetprice (intPrice ) {                 This. Price =Price ; //set a change in salary         This. setchanged (); //notifies the observer to execute, and internal is the call to all observers of the Update method, through the interface implementation.          This. Notifyobservers ( This. name);//Lunch can also be used as a reference    }    }
View Code

Test the Main method: Test.java

 PackageCn.liuning.watch; Public classTest { Public Static voidMain (string[] args) {//initialized by the ObserverUser User =NewUser (); //Add an observerUser.addobserver (NewAdmin ()); User.setname ("John Doe"); //when the price changes, the viewer executes the Update method. User.setprice (100); }}
View Code

The observer pattern in Java internal implementation

Related Article

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.