public class PriceObservable extends Observable { private Double price; public PriceObservable(Double price){this.price=price;} public void setPrice(Double price){ this.price=price; super.setChanged(); super.notifyObservers(price); } public Double getPrice(){ return price; } public static void main(String args[]) { PriceObservable po=new PriceObservable(10.5); Observer ob1=new Observer("纽交所"); Observer ob2=new Observer("深交所"); Observer ob3=new Observer("上交所"); po.addObserver(ob1); po.addObserver(ob2); po.addObserver(ob3); po.setPrice(20.5); }}
public class Observer implements java.util.Observer { private String name; public Observer(String name){ this.name=name; } @Override public void update(Observable o, Object object) { System.out.println("..."); if(object instanceof Double) { System.out.println(name + "观察到价格" + "改变为:" + (Double) object); } } }
写个观察者模式
最新推荐文章于 2022-09-22 15:22:11 发布