Observer Observer pattern

Source: Internet
Author: User

The Observer pattern (sometimes referred to as the publish-subscribe subscribe> pattern, the Observer pattern defines a one-to-many dependency, allowing multiple observer objects to listen to a Subject object at the same time, which notifies all observer objects when a change in state occurs, allowing them to automatically update themselves.

The composition of the Observer pattern

Abstract Theme Role : All references to observer objects are saved in a collection, and each abstract theme role can have any number of observers. Abstract topics provide an interface that can add and remove observer roles. It is generally implemented with an abstract class and interface.

Abstract Observer Role : Define an interface for all specific observers and update yourself when you get notifications for a topic.

specific topic role : Notifies all registered observers when the internal state of a specific topic changes. A specific theme role is typically implemented with a subclass.

specific Observer role : This role implements the update interfaces required by the abstract observer role in order to reconcile the state of itself with the state of the topic. Typically implemented with a subclass. If necessary, the specific observer role can save a reference to a specific topic role.

Here is a simple implementation, in order to understand, here do not abstract topics, directly write specific topics and the implementation of the idea of the Observer:

1. The viewer

/**@author*/Publicinterface  watcher    { /**      * Update information      @param  what     obj needs to be changed */public     void update (Object obj);}

2. Subject, also being observed

/*** Subject, also being observed * when the subject changes, notify the observer to update the information *@authorCharm _ Niche **/ Public Abstract classTopic {//list of observers who need to be notified    PrivateList<watcher> watcherlist =NewArraylist<watcher>(); /*** Add observer to Observer list *@paramW*/     Public voidAddwatcher (Watcher W) {Watcherlist.add (w); }        /*** Remove observers from the Observer list *@paramW*/     Public voidRemovewatcher (Watcher W) {Watcherlist.remove (w); }        /*** Notify observers in the list of observers, change information *@paramupdatecontent What needs to be changed*/     Public voidNotifywatcher (Object updatecontent) { for(Watcher w:watcherlist) {w.update (updatecontent); }    }}

3. You can write multiple observer subclasses and then add to the subject's list of observers, and when the subject changes, call Notifywatcher () to notify the observer to make the change.

The JDK API's Java.util package already encapsulates the theme class observable, and the abstract Observer interface Observer, we just have to inherit them to apply our publish subscription model.

Application Examples:

There is a book "Java", when the price changes, to notify users, to send users email and text messages

First, the Observer class is going to send notifications, and the class that sends the email and text messages after the change is the observer.

1. Book Books

 Public classbook{PrivateString bookname = "Java"; Private floatPrice = 40;//Original Price     PublicBook (String BookName,floatPrice ) {        Super();  This. BookName =BookName;  This. Price =Price ; }     PublicBook () {} PublicString Getbookname () {returnBookName; }     Public floatGetPrice () {returnPrice ; } @Override PublicString toString () {return"Book [bookname=" + BookName + ", price=" + Price + "]"; }    }

2. The observed bookobservable inherit java.util.Observable

/*** observed, inheriting observable * * When price changes, notify each observer *@authorCharm _ Niche *@version[version number, February 26, 2016]*/ Public classBookobservableextendsobservable{//Book price changes, call the method, notify the Observer     Public voidnoticewatcher (book book) {//change the state of the observed person        Super. setchanged (); //when the book price is changed, inform the viewer        Super. Notifyobservers (book); }}

3. Observer class, accept notification, implement observer interface

/*** Viewer * When book price changes, send email to user * *@authorCharm _ Niche *@version[version number, February 26, 2016]*/ Public classBookobserveremailImplementsobserver{ Book Book=NewBook (); /*** Observable O: Object observed * Object ARG: Specific business object*/@Override Public voidUpdate (Observable o, Object Arg) {Book Update=(book) Arg; System.out.println ("Email: Book" +update.getbookname () + "reduced price, now prices are:" +Update.getprice ()); //receive notifications, update informationBook =Update; }         Public voidPrintbookinfo () {System.out.println ("E-mail book information:" +Book ); }    }
/*** Viewer * When book price changes, send SMS to user * *@authorCharm _ Niche *@version[version number, February 26, 2016]*/ Public classBookobservermobileImplementsobserver{ Book Book=NewBook (); /*** Observable O: Object observed * Object ARG: Specific business object*/@Override Public voidUpdate (Observable o, Object Arg) {Book Update=(book) Arg; System.out.println ("SMS: Book" +update.getbookname () + "reduced price, now prices are:" +Update.getprice ()); //receive notifications, update informationBook =Update; }         Public voidPrintbookinfo () {System.out.println ("Mobile's book Info:" +Book ); }}

4. Testing

 Public Static voidMain (string[] args) { book Book=NewBook ("Java", 36);//Book original Price is 40, reduced to//create all observers who need to be notifiedBookobserveremail Observeremail =NewBookobserveremail (); Bookobservermobile Observermobile=NewBookobservermobile (); //To create the person being observedBookobservable observable =Newbookobservable (); //list of observers added to the observer who need to be notifiedObservable.addobserver (Observeremail);                Observable.addobserver (Observermobile); //call the notification method to notify the reduced book informationobservable.noticewatcher (book); //View updated book information for viewersSystem.out.println ("---------------Updated book Information-----------------");        Observeremail.printbookinfo ();    Observermobile.printbookinfo (); }

5. Results

SMS: Book Java prices, now the price is: 36.0Email: Book Java prices, now the price is:36.0---------------updated book information-----------------  e-Mail Book information: book [BookName=java, price=36.0]mobile Books information: [BookName=java, price=36.0]

Observer 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.