Defines a one-to-many dependency between objects, so that whenever an object changes state, all objects that depend on it are notified and automatically updated.
The Observer mode provides a means for the associated object to synchronize communication between an object and other objects that depend on it.
Java provides the Obeservable class and the Observer interface.
For example, home buyers are observers, and house prices are observed, and changes in house prices are the concern of the observer.
/*** The person being observed *@authorSoyoungboy **/ Public classHouseextendsObservable {//Rates Private floatPrice ; PublicHouse (floatPrice ) { This. Price =Price ; } Public floatGetPrice () {returnPrice ; } Public voidSetprice (floatPrice ) { //Set Change Point Super. setchanged (); //notify the viewer that the price has changed Super. Notifyobservers (price); This. Price =Price ; } @Override PublicString toString () {return"House [price=" + Price + "]"; }}
/*** Rate Watcher *@authorSoyoungboy **/ Public classHouseobserverImplementsObserver {//name of the purchaser PrivateString name; Publichouseobserver (String name) { This. Name =name; } @Override Public voidUpdate (Observable o, Object Arg) {if(ARGinstanceofFloat) {System.out.println ("The name observes that the price change is:" +( (Float) arg). Floatvalue ()); } }}
Public classTest { Public Static voidMain (string[] args) { House House=NewHouse (10000); Houseobserver Houseobserver=NewHouseobserver ("Purchaser A"); Houseobserver HouseObserver1=NewHouseobserver ("House Buyer B"); Houseobserver HouseObserver2=NewHouseobserver ("House buyer C"); //the listener who added the rateHouse.addobserver (Houseobserver); House.addobserver (HouseObserver1); House.addobserver (HouseObserver1); System.out.println (House.tostring ()); House.setprice (20000); System.out.println (House.tostring ()); House.setprice (30000); System.out.println (House.tostring ()); }}
The result is:
House [price=10000.0]name observed that the price change was:20000.0name observed price change:20000.0 House[prices =20000.0 ]name observed that the change in house prices was:30000.0name observed the change in house prices to:30000.0 houses[price = 30000.0]
Design pattern--observer design pattern