小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

Java常用類庫(kù)--觀察者設(shè)計(jì)模式( Observable類Observer接口)

 zhngjan 2014-07-11
   


如果要想實(shí)現(xiàn)觀察者模式,則必須依靠java.util包中提供的Observable類和Observer接口。
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import java.util.* ; 
class House extends Observable{ // 表示房子可以被觀察 
    private float price ;// 價(jià)錢 
    public House(float price){ 
        this.price = price ; 
    
    public float getPrice(){ 
        return this.price ; 
    
    public void setPrice(float price){ 
        // 每一次修改的時(shí)候都應(yīng)該引起觀察者的注意 
        super.setChanged() ;    // 設(shè)置變化點(diǎn) 
        super.notifyObservers(price) ;// 價(jià)格被改變 
        this.price = price ; 
    
    public String toString(){ 
        return "房子價(jià)格為:" + this.price ; 
    
};  
class HousePriceObserver implements Observer{ 
    private String name ; 
    public HousePriceObserver(String name){ // 設(shè)置每一個(gè)購(gòu)房者的名字 
        this.name = name ; 
    
    public void update(Observable o,Object arg){ 
        if(arg instanceof Float){ 
            System.out.print(this.name + "觀察到價(jià)格更改為:") ; 
            System.out.println(((Float)arg).floatValue()) ; 
        
    
}; 
public class ObserDemo01{ 
    public static void main(String args[]){ 
        House h = new House(1000000) ; 
        HousePriceObserver hpo1 = new HousePriceObserver("購(gòu)房者A") ; 
        HousePriceObserver hpo2 = new HousePriceObserver("購(gòu)房者B") ; 
        HousePriceObserver hpo3 = new HousePriceObserver("購(gòu)房者C") ; 
        h.addObserver(hpo1) ; 
        h.addObserver(hpo2) ; 
        h.addObserver(hpo3) ; 
        System.out.println(h) ; // 輸出房子價(jià)格 
        h.setPrice(666666) ;    // 修改房子價(jià)格 
        System.out.println(h) ; // 輸出房子價(jià)格 
    
};

 

 
運(yùn)行結(jié)果:
房子價(jià)格為:1000000.0
購(gòu)房者C觀察到價(jià)格更改為:666666.0
購(gòu)房者B觀察到價(jià)格更改為:666666.0
購(gòu)房者A觀察到價(jià)格更改為:666666.0
房子價(jià)格為:666666.0

    本站是提供個(gè)人知識(shí)管理的網(wǎng)絡(luò)存儲(chǔ)空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請(qǐng)注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購(gòu)買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊一鍵舉報(bào)。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評(píng)論

    發(fā)表

    請(qǐng)遵守用戶 評(píng)論公約

    類似文章 更多