class Watcher implements Observer { public void update(Observable obj, Object arg ) { System.out.println("Update() called, count is " + ((Integer) arg).intValue()); } }
BeingWatched.java代码
import java.util.*;
class BeingWatched extends Observable { void counter( int period ) { for(;period >=0; period-- ) { setChanged(); notifyObservers( new Integer ( period ) ); try { Thread.sleep(100); } catch( InterruptedException e) { System.out.println("Sleep interrupeted" ); } } } };
ObserverDemo.java代码
public class ObserverDemo { public static void main( String[] args ) { BeingWatched observed = new BeingWatched(); Watcher observing = new Watcher(); observed.addObserver( observing); observed.counter(10); } };
执行结果
Update() called, count is 10 Update() called, count is 9 Update() called, count is 8 Update() called, count is 7 Update() called, count is 6 Update() called, count is 5 Update() called, count is 4 Update() called, count is 3 Update() called, count is 2 Update() called, count is 1 Update() called, count is 0