25. Viewer mode observable and Observer in Java
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 class House extends observable{2 private Double price, 3 public house (double price) {4 this.price=price; 5< c5/>} 6 Public double GetPrice () {7 return price, 8 } 9 public void Setprice (double price) {Ten if ( This.price!=price) { this.price=price;12 setchanged (); The label price has been changed by this.notifyobservers (prices); Notifies the observer that the data has been changed }15 }16 @Override17 public String toString () {"The current rate is:" +price;19 }20}
Home buyers Realize
1 class Housepriceobserver implements observer{2 private String name; 3 public housepriceobserver (String Name) {4 this.name=name; 5 } 6 @Override 7 public void Update (Observable o, Object Arg) {8 //Here it is better to judge a Whether the notice is from the house price, it is possible to come from another Place 9 if (o instanceof House) { System.out.println ("Shopper" +name+ "observed that the price has been adjusted to:" +arg); }12 }13}
Run
1 House house=new House (10000); 2 housepriceobserver a=new housepriceobserver ("A"); 3 Housepriceobserver b=new housepriceobserver ("B"); 4 housepriceobserver c=new housepriceobserver ("C"); 5 House.addobserver (A); 6 House.addobserver (B); 7 House.addobserver (C); 8 System.out.println (house); 9 House.setprice (6000); House.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
Observer patterns observable and observer in Java