less than 1 minute read

Observer pattern - one subject many observers, state changes in the subject must be notified to all observers.
Observers first register with the subject, once the states the subject calls the notify method in the registered observers.

public class NotificationService {
  public List<Listener> listeners;
  public void notifyListeners() {
    for (Listener listener : listeners) {
	  listener.notify();
	}
  }
}
public interface Listener {
  public void notify();
}
public class MyService implements Listener {
  public void notify() {
    //when i receive a message i do something

	//for example notify my app

  }
}

Register MyService:

NotificationService notifyService = new NotificationService();
MyService theService = new MyService();
notifyService.getListeners().add(theService);

Tags:

Updated:

Comments