Java Watcher pattern

Source: Internet
Author: User

/***/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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.