原文鏈接:http://www.2cto.com/kf/201310/253013.html

如果要想實現觀察者模式,則必須依靠java.util包中提供的Observable類和Observer接口。
| 123456789101112131415161718192021222324252627282930313233343536373839404142434445 | import java.util.* ; class House extends Observable{ // 表示房子可以被觀察 PRivate float price ;// 價錢 public House(float price){ this.price = price ; } public float getPrice(){ return this.price ; } public void setPrice(float price){ // 每一次修改的時候都應該引起觀察者的注意 super.setChanged() ; // 設置變化點 super.notifyObservers(price) ;// 價格被改變 this.price = price ; } public String toString(){ return "房子價格為:" + this.price ; } }; class HousePriceObserver implements Observer{ private String name ; public HousePriceObserver(String name){ // 設置每一個購房者的名字 this.name = name ; } public void update(Observable o,Object arg){ if(arg instanceof Float){ System.out.print(this.name + "觀察到價格更改為:") ; System.out.println(((Float)arg).floatValue()) ; } } }; public class ObserDemo01{ public static void main(String args[]){ House h = new House(1000000) ; HousePriceObserver hpo1 = new HousePriceObserver("購房者A") ; HousePriceObserver hpo2 = new HousePriceObserver("購房者B") ; HousePriceObserver hpo3 = new HousePriceObserver("購房者C") ; h.addObserver(hpo1) ; h.addObserver(hpo2) ; h.addObserver(hpo3) ; System.out.println(h) ; // 輸出房子價格 h.setPrice(666666) ; // 修改房子價格 System.out.println(h) ; // 輸出房子價格 } }; |
新聞熱點
疑難解答