If you want to implement the observer pattern, you must rely on the observable class and observer interfaces provided in the Java.util package
Viewer design Pattern
Now 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 buyers are the observers, and the price they pay attention to is the observed
Where required, the observer needs to inherit the observable class and observe the need to implement the Observer interface
The specific implementation is as follows
The realization of the house price
1 classHouseextendsobservable{2 Private DoublePrice ;3 PublicHouse (DoublePrice ) {4 This. price=Price ;5 }6 Public DoubleGetPrice () {7 returnPrice ;8 }9 Public voidSetprice (DoublePrice ) {Ten if( This. price!=Price ) { One This. price=Price ; ASetchanged ();//The label price has been changed - This. Notifyobservers (price);//notifies the Observer that the data has been changed - } the } - @Override - PublicString toString () { - return"Current rate is:" +Price ; + } -}
Home buyers Realize
1 classHousepriceobserverImplementsobserver{2 PrivateString name;3 Publichousepriceobserver (String name) {4 This. name=name;5 }6 @Override7 Public voidUpdate (Observable o, Object Arg) {8 //It's better to judge whether the notice comes from the house price, possibly from somewhere else.9 if(OinstanceofHouse ) {TenSYSTEM.OUT.PRINTLN ("Shopper" +name+ "observed that the house price has been adjusted to:" +Arg); One } A } -}
Run
1House house=NewHouse (10000);2Housepriceobserver a=NewHousepriceobserver ("A");3Housepriceobserver b=NewHousepriceobserver ("B");4Housepriceobserver c=NewHousepriceobserver ("C");5 House.addobserver (A);6 House.addobserver (B);7 House.addobserver (C);8 System.out.println (house);9House.setprice (6000);TenHouse.setprice (8000);
The result of the operation is:
Current rate is: 10000.0
Shopper C observes that the house price has been adjusted to: 6000.0
Shopper B observes that the house price has been adjusted to: 6000.0
Shopper a observes that the room rate has been adjusted to: 6000.0
Shopper C observes that the house price has been adjusted to: 8000.0
Shopper B observes that the house price has been adjusted to: 8000.0
Shopper a observes that the room rate has been adjusted to: 8000.0
25. Viewer mode observable and Observer in Java