To implement the Observer mode, you must rely on the Observable class and Observer interface provided in the java. util package.
Import java. util. *; class House extends Observable {// indicates that the House can be viewed as private float price; // price public House (float price) {this. price = price;} public float getPrice () {return this. price;} public void setPrice (float price) {// The observer's attention should be paid to each modification. setChanged (); // set the change point super. yyobservers (price); // The price is changed this. price = price;} public String toString () {return "House price:" + this. price ;}}; class HousePriceObserver implements Observer {private String name; public HousePriceObserver (String name) {// set the name of each buyer this. name = name;} public void update (Observable o, Object arg) {if (arg instanceof Float) {System. out. print (this. name + "observed price changed to:"); System. out. println (Float) arg ). floatValue () ;}}; public class ObserDemo01 {public static void main (String args []) {House h = new House (1000000 ); export hpo1 = new HousePriceObserver ("buyer A"); HousePriceObserver hpo2 = new HousePriceObserver ("buyer B"); HousePriceObserver hpo3 = new HousePriceObserver ("buyer C"); h. addObserver (hpo1); h. addObserver (hpo2); h. addObserver (hpo3); System. out. println (h); // output house price h. setPrice (666666); // modify the house price System. out. println (h); // output house price }};
Result: The house price is: 1000000.0 buyers C observed the price changed to: 666666.0 buyers B observed the price changed to: 666666.0 buyers A observed the price changed to: 666666.0 house price: 666666.0