Select Page

Observer

Observer

Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

Source code

/**  * Knows its observers. Any number of Observer objects  * may observe a subject. Provides an interface for attaching  * and detaching Observer objects.  * @role __Subject  */ public class Subject {         private ArrayList observers = new ArrayList();        public void attach(Observer observer) {                 observers.add(observer);        }          public void detach(Observer observer) {                 int idx = observers.indexOf(observer);                if (idx != -1) {                         observers.remove(idx);                }         }          protected void notifyObservers() {                 Iterator it = observers.iterator();                while (it.hasNext()) {                         ((Observer) it.next()).update(this);                }         }  }  /**  * Defines an updating interface for objects that  * should be notified of changes in a subject.  * @role __Observer  */ public interface Observer {         /**   * Update method.   */         public void update(Subject subject);}  /**  * Stores state of interest to ConcreteObserver objects.  * Sends a notification to its observers when its state changes.  */ public class ConcreteSubject extends Subject {          // add your subject's specific stuff here }  /**  * Implements the Observer updating interface to keep   * its state consistent with the subject's.  */ public class ConcreteObserver implements Observer {         public void update(Subject subject) {                 // put your code here         }  }   
0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments

Categories

0
Would love your thoughts, please comment.x
()
x