Select Page



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);                }         }  }  /**  * 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         }  }   

About The Author

Cédric Walter

I worked with various Insurances companies across Switzerland on online applications handling billion premium volumes. I love to continuously spark my creativity in many different and challenging open-source projects fueled by my great passion for innovation and blockchain technology.In my technical role as a senior software engineer and Blockchain consultant, I help to define and implement innovative solutions in the scope of both blockchain and traditional products, solutions, and services. I can support the full spectrum of software development activities, starting from analyzing ideas and business cases and up to the production deployment of the solutions.I'm the Founder and CEO of Disruptr GmbH.