/***/Publicinterface watcher {// status is The state public void update (String status) that was observed to pass over;}
Importjava.util.LinkedList;/**abstract the observed person*/ Public Abstract classwatched {/**The Observer object used to save the registration*/ protectedLinkedlist<watcher> watcherlist =NewLinkedlist<watcher>(); /**registering the Observer object*/ Public Abstract voidAdd (Watcher Watcher); /**Delete Observer Object*/ Public Abstract voidRemove (Watcher watcher); /**notifies all registered observer objects*/ Public Abstract voidnotifywatchers ();}
// the specific observer Public class Implements Watcher { @Override publicvoid update (String status) { System.out.println ( this + "monitor status" + Status );} }
/**specific observers: Add and Remove methods are best combined with synchronization*/ Public classGirlextendswatched {PrivateString status; Public voidsetStatus (String status) { This. Status =status; } @Override Public synchronized voidAdd (Watcher Watcher) {Watcherlist.add (watcher); } @Override Public synchronized voidRemove (Watcher Watcher) {watcherlist.remove (watcher); } @Override Public voidnotifywatchers () { for(Watcher w:watcherlist) {w.update (status); } }}
Test code and results
Public classTest { Public Static voidMain (string[] args)throwsException {Girl Girl=NewGirl (); for(inti = 0; I < 3; i++) {Girl.add (NewBoy ()); } girl.setstatus ("Happy"); Girl.notifywatchers (); TimeUnit.SECONDS.sleep (1); Girl.setstatus ("Unhappy"); Girl.notifywatchers (); }}
Reference:
Http://www.cnblogs.com/mengdd/archive/2013/02/07/2908929.html
Http://www.cnblogs.com/mengdd/archive/2013/02/07/2908929.html
Java Watcher pattern