标签:set http out 继承 lang 参数 bsp add doc
Observer对象是观察者,Observable对象是被观察者。
官网api文档:http://docs.oracle.com/javase/7/docs/api/
void update(Observable o, Object arg)
形参Object arg,对应一个由notifyObservers(Object arg);传递来的参数,当执行的是notifyObservers();时,arg为null。
被观察者:ServerManager
package com.test.observer; import java.util.Observable; public class ServerManager extends Observable { private int data = 0; public int getData(){ return data; } public void setData(int i){ if(this.data != i){ this.data = i;setChanged();} notifyObservers(); //只有在setChange()被调用后,notifyObservers()才会去调用update(),否则什么都不干。 } } } }
观察者一:AObserver
import java.util.Observable; import java.util.Observer; public class AObserver implements Observer { public AObserver(ServerManager sm) { super(); // TODO Auto-generated constructor stub sm.addObserver(this); //注册加入观察者 } @Override public void update(Observable arg0, Object arg1) { System.out.println("AObserver receive:Data has changed to "+((ServerManager) arg0).getData()); } }
观察者二:BObserver
import java.util.Observable; import java.util.Observer; public class BObserver implements Observer { public BObserver(ServerManager sm) { super(); sm.addObserver(this); //注册加入观察者 } @Override public void update(Observable o, Object arg) { // TODO Auto-generated method stub System.out.println("BObserver receive:Data has changed to "+((ServerManager) o).getData()); } }
测试:
public class TestDemo { public static void main(String[] args) { // TODO Auto-generated method stub ServerManager sm = new ServerManager(); AObserver a = new AObserver(sm); BObserver b = new BObserver(sm); sm.setData(5); sm.deleteObserver(a); //注销观察者,以后被观察者有数据变化就不再通知这个已注销的观察者 sm.setData(10); } }
运行结果:
标签:set http out 继承 lang 参数 bsp add doc
原文地址:http://www.cnblogs.com/gongjian/p/6104766.html