Java自学--观察者设计模型

来源:互联网 发布:好的桌面软件 编辑:程序博客网 时间:2024/05/16 01:07

被观察的事物发生变化后将会将变化的东西高数观察者

eg: 房子价格放生改变,买房者需要第一时间知道。

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

public void update(Observable o,Object arg)
方法中  o为表示Obervable 对象

arg 表示观察的内容

0 0
原创粉丝点击