zoukankan      html  css  js  c++  java
  • 观察者设计模式( Observable类Observer接口)

    如果要想实现观察者模式,则必须依靠Java.util包中提供的Observable类和Observer接口。

    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

  • 相关阅读:
    XE8下安装IntraWeb 14.0.40和D7下安装IntraWeb 11.0.63破解版的正确方法
    网易博客打不开怎么办
    SQL SERVER 导入EXCEL的存储过程
    TMemoryStream、String与OleVariant互转
    【转载】Delphi Idhttp的get和post方法
    sqlserver得到行号
    Delphi 中的 XMLDocument 类详解(5)
    10款免费且开源的项目管理工具
    iOS开发者必备:九大设计类工具
    15个步骤创立技术公司,并收获千万用户(完结)
  • 原文地址:https://www.cnblogs.com/ganchuanpu/p/6724534.html
Copyright © 2011-2022 走看看