The Observer pattern defines a one-to-many dependency that allows multiple observer objects to listen to a Subject object at the same time. When the subject object changes in state, all observer objects are notified so that they can automatically update themselves. Observer Pattern Composition:
Abstract Theme role: All references to observer objects are saved in a collection, and each abstract theme role can have any number of observers. Abstract topics provide an interface that can add and remove observer roles. Typically implemented with an abstract class or interface.
Abstract Observer role: Define an interface for all specific observers and update yourself when you get notifications for a topic.
Specific topic role: Notifies all registered observers when the internal state of a specific topic changes. A specific theme role is typically implemented with a subclass.
Specific observer role: This role implements the update interfaces required by the abstract observer role in order to reconcile the state of itself with the state of the topic. If necessary, the specific observer role can save a reference to a specific topic role. Typically implemented with a subclass.
1 PackageObserver;2 3 Public classConcretewatcherImplementsWatcher4 {5 @Override6 Public voidUpdate (String str)7 {8 System.out.println (str);9 }Ten One } A - PackageObserver; - the Importjava.util.ArrayList; - Importjava.util.List; - - Public classConcretewatchedImplementswatched + { - Privatelist<watcher> list =NewArraylist<watcher>(); + A @Override at Public voidAddwatcher (Watcher Watcher) - { - List.add (watcher); - } - - @Override in Public voidRemovewatcher (Watcher Watcher) - { to List.remove (watcher); + } - the @Override * Public voidnotifywatchers (String str) $ {Panax Notoginseng for(Watcher Watcher:list) - { the watcher.update (str); + } A } the + } - $ PackageObserver; $ - Public InterfaceWatcher - { the Public voidUpdate (String str); - }Wuyi the PackageObserver; - Wu Public Interfacewatched - { About Public voidAddwatcher (Watcher watcher); $ - Public voidRemovewatcher (Watcher watcher); - - Public voidnotifywatchers (String str); A } + the PackageObserver; - $ Public classTest the { the Public Static voidMain (string[] args) the { theWatched girl =Newconcretewatched (); - inWatcher Watcher1 =NewConcretewatcher (); theWatcher Watcher2 =NewConcretewatcher (); theWatcher Watcher3 =NewConcretewatcher (); About the Girl.addwatcher (watcher1); the Girl.addwatcher (watcher2); the Girl.addwatcher (WATCHER3); + -Girl.notifywatchers ("123"); the Bayi Girl.removewatcher (watcher2); the theGirl.notifywatchers ("456"); - - the } the}
Observer Mode (OBSERVER)