To put it simply, the observer pattern defines a one-to-many dependency that allows one or more observer objects to monitor a subject object. Such a change in state of a Subject object informs all those observer objects that depend on this object, so that these observer objects can be automatically updated.
Not much to say, directly give the realization:
Example 1:
/** * Example of a single subscriber to an event * @author Yongxing.shao * */Public Class Oneobserverexample {Public Static voidMain(String[]Args) {IObserverObserver= New Observer();EventnotifierNotifier= New Eventnotifier(Observer);Notifier.DoWork();}}An observer interface that is interested in an eventInterface IObserver {Public voidProcessinterestedevent();}/** * When an event occurs, you need to notify the object implementing the IObserver interface and call the Interesingevent () method * @author Yongxing.shao * */Class Eventnotifier {Private IObserverObserver; ObserversPrivate Booleansomethinghappened; Flag whether the event occurredPublic Eventnotifier(IObserverObserver) {This.Observer=Observer;This.somethinghappened= False;}Public voidDoWork() {somethinghappened= True;If (somethinghappened) {When an event occurs, this method of calling the interface is used to notifyObserver.Processinterestedevent();}}}/** * Viewer Implementation * @author Yongxing.shao * */Class Observer Implements IObserver {Private EventnotifierEn;Public Observer() {Create a new event Notifier object and pass yourself to itThis.en = neweventnotifier (this}//when implementing an event, the method of actually handling the event void Processinterestedevent () Span class= "PLN" > {system.. Println "observer:event happened" }} /span>
Example 2:
/** * There are multiple subscribers to an event * @author Yongxing.shao * */Public Class Manyobserverexample {Public Static voidMain(String[]Args) {EventnotifierNotifier= New Eventnotifier();IObserverObservera= New Observer("Observer A");IObserverObserverb= New Observer("Observer B");RegistNotifier.Regist(Observera);Notifier.Regist(Observerb);Notifier.DoWork();}}/** * Observer interface for an event of interest * @author Yongxing.shao * */Interface IObserver {Public voidProcessinterestedevent(String Event);}Class Observer Implements IObserver {Private StringName;Public Observer(StringName) {This.Name=Name;}The method that actually handles the event when the implementation event occursPublic voidProcessinterestedevent(String Event) {System.Out.println(Name+ ": [" + Event + "] happened.");}}/** * When an event occurs, you need to notify the object implementing the IObserver interface and call the Interesingevent () method * @author Yongxing.shao * */Class Eventnotifier {Private List<IObserver>Observers= New ArrayList<IObserver> (); ObserversPublic voidRegist(IObserverObserver) {Observers.Add(observer); }public Dowork () {for (iobserver Observer : Observers) { observer. "Sample Event" }}} /span>
http://blog.csdn.net/xyls12345/article/details/26386885
Java Watcher mode (GO)