Java Common Class Library--observer design pattern

Source: Internet
Author: User

Viewer Design Patternnow a lot of buyers are watching the price change of the house, every time the house price changes, all the buyers can be observed. In fact, the above buyers are the observers, they are concerned about the price of the house.
if you want to implement the observer pattern, you must rely on the observable class and observer interfaces provided in the Java.util package. view the API as follows:
View the observable classes in the Java.util package as follows:
Java.util class Observable Java.lang.Object successor Java.util.Observable Public classObservableextendsobject This class represents the observable object in the Model view paradigm, or "data."            You can subclass it to represent the object that the application wants to observe. A observable object can have one or more observers. The observer can be any object that implements the Observer interface. After a observable instance is changed
, call Observable's notifyobservers
Method notifies the Observer that the instance has changed by calling the Observer's Update method. The order in which notifications are sent is not specified. The default implementations provided in the Observable class will notify observers according to the order in which they are registered, but subclasses may change this order.
This can be used to send notifications on separate threads in a non-fixed order, or to ensure that their subclasses follow the order they choose. Note that this notification mechanism is thread-independent and completely separate from the wait and notify mechanisms of the Object class. When a new observable object is created, its observer set is empty. When and only if the Equals method is returned for two observerstrueonly when they are considered to be the same. Start with the following versions: JDK1.0See also: Notifyobservers (), Notifyobservers (Java.lang.Object), Observer, Observer.update (java.util.Observable, Java.lang.Object) Construction Method Summary Observable () constructs a Observable with 0 observers. Method Summaryvoidaddobserver (Observer O) If the observer differs from an existing observer in the collection, the observer is added to the object's observer set. protected voidclearchanged () indicates that the object no longer changes, or that it has notified the most recent change to all its observers, so the HasChanged method returnsfalse. intcountobservers () returns the number of observers for the Observable object. voiddeleteobserver (Observer o) removes an observer from the object's collection of observers. voiddeleteobservers () Clears the list of observers so that the object no longer has any observers. BooleanhasChanged () tests whether the object has changed. voidnotifyobservers () notifies all its observers if the HasChanged method indicates that the object has changed, and calls the Clearchanged method to indicate that the object is no longer changing. voidnotifyobservers (Object arg) notifies all its observers if the HasChanged method indicates that the object has changed, and calls the Clearchanged method to indicate that the object is no longer changing. protected voidsetchanged () marks this Observable object as a changed object; Now the HasChanged method returnstrue. Methods inherited from Class Java.lang.Object clone, Equals, Finalize, GetClass, Hashcode, notify, Notifyall, toString, wait, wait, wait Construction method Details Observable PublicObservable () constructs a Observable with 0 observers. Method Details Addobserver Public voidaddobserver (Observer O) If the observer differs from an existing observer in the collection, the observer is added to the object's observer set. The order in which notifications are sent to multiple observers is not specified. See comments for this class. Parameters: O-the viewer to add. Thrown: NullPointerException-If the parameter O isNULL. Deleteobserver Public voiddeleteobserver (Observer o) removes an observer from the object's collection of observers. Pass to this methodNULLwill invalidate it. Parameters: O-the viewer to delete. Notifyobservers Public voidnotifyobservers () notifies all its observers if the HasChanged method indicates that the object has changed, and calls the Clearchanged method to indicate that the object is no longer changing. Each observer has its Update method with two invocation parameters: the observable object and theNULL. In other words, this method is equivalent to: Notifyobservers (NULLSee also: clearchanged (), hasChanged (), Observer.update (java.util.Observable, Java.lang.Object) notifyobs Ervers Public voidnotifyobservers (Object arg) notifies all its observers if the HasChanged method indicates that the object has changed, and calls the Clearchanged method to indicate that the object is no longer changing. Each observer has its Update method with two invocation parameters: the observable object and the arg parameter. Parameter: Arg-any object. See also: clearchanged (), hasChanged (), Observer.update (java.util.Observable, Java.lang.Object) deleteobservers Public voiddeleteobservers () Clears the list of observers so that the object no longer has any observers. Setchangedprotected voidsetchanged () marks this Observable object as a changed object; Now the HasChanged method returnstrue. Clearchangedprotected voidclearchanged () indicates that the object no longer changes, or that it has notified the most recent change to all its observers, so the HasChanged method returnsfalse. This method is called automatically by the Notifyobservers method. See also: Notifyobservers (), Notifyobservers (java.lang.Object) hasChanged Public BooleanhasChanged () tests whether the object has changed. Returns: returns when and only if the Setchanged method was recently called on this object, not the Clearchanged method .true; otherwise returnedfalse. See also: clearchanged (), setchanged () countobservers Public intcountobservers () returns the number of observers for the Observable object. Returns: The number of observers for the object.

Examples of program code are as follows:

    ImportJava.util.* ; classHouseextendsobservable{//that the house can be observed .        Private floatPrice;//Price         PublicHouse (floatPrice ) {               This. Price =Price ; }           Public floatGetPrice () {return  This. Price; }           Public voidSetprice (floatPrice ) {              //every modification should be noticed by the observer.            Super. setchanged ();//Set Change Point            Super. Notifyobservers (price);//Price is changed             This. Price =Price ; }           PublicString toString () {return"The price of the house is:" + This. Price;       }      }; classHousepriceobserverImplementsobserver{PrivateString name;  PublicHousepriceobserver (String name) {//set the name of each purchaser             This. Name =name; }           Public voidUpdate (Observable o,object arg) {if(ARGinstanceofFloat) {System.out.print ( This. Name + "observed price changed to:") ;              System.out.println ((Float) arg). Floatvalue ());      }          }      };  Public classobserdemo01{ Public Static voidMain (String args[]) {House H=NewHouse (1000000) ; Housepriceobserver HPO1=NewHousepriceobserver ("Purchaser A") ; Housepriceobserver Hpo2=NewHousepriceobserver ("House Buyer B") ; Housepriceobserver HPO3=NewHousepriceobserver ("House buyer C") ;              H.addobserver (HPO1);              H.addobserver (HPO2);              H.addobserver (HPO3); System.out.println (h); //Output house priceH.setprice (666666);//Revise house priceSystem.out.println (h);//Output house price        }      }; 

Summarize:

The two parameters in the Update method in the Observer interface:O: The object that specifically represents the observable class that issued the notification. That indicates which of the observers sent the notification. ARG: The content that needs to be observed.  the object to be observed by the observer is the class that inherits from the observable. You must call the Super.setchanged () method and the Notifyobservers (XXX) method when sending notifications.  This design pattern is a mechanism of Java itself, and it can be implemented without using the Observer interface and the observable class, but it is more complex.

Java Common Class Library--observer design 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.