【Java常用類庫】_觀察者設計模式筆記

來源:互聯網
上載者:User

【Java常用類庫】_觀察者設計模式筆記

本章目標:
瞭解觀察者模式的作用
掌握Observable類Observer

注意:核心就中設定觀察點上

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) ;    // 輸出房子價格    }};

輸出:(可以看出觀察者會在修改時輸出內容)

房子價格為:1000000.0
購房者C觀察到價格更改為:666666.0
購房者B觀察到價格更改為:666666.0
購房者A觀察到價格更改為:666666.0
房子價格為:666666.0

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.