Common Java class libraries-Observer design patterns (Observable class Observer Interface) and observableobserver
Link: http://www.2cto.com/kf/201310/253013.html
To implement the Observer mode, you must rely on the Observable class and Observer interface provided in the java. util package.
123456789101112131415161718192021222324252627282930313233343536373839404142434445 |
import java.util.* ; class House extends Observable{ // Indicates that the House can be observed private float price ; // Price public House( float price){ this .price = price ; } public float getPrice(){ return this .price ; } public void setPrice( float price){ // The observer should pay attention to each modification. super .setChanged() ; // Set the Change Point super .notifyObservers(price) ; // Price 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 + "The price was changed :" ) ; System.out.println(((Float)arg).floatValue()) ; } } }; public class ObserDemo01{ public static void main(String args[]){ House h = new House( 1000000 ) ; HousePriceObserver hpo1 = new HousePriceObserver( "Homebuyer" ) ; HousePriceObserver hpo2 = new HousePriceObserver( "Buyer B" ) ; HousePriceObserver hpo3 = new HousePriceObserver( "Homebuyer 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