Observer pattern
The observer pattern is sometimes called the Publish/subscribe pattern , which defines a one-to-many dependency that allows multiple observer objects to listen to a Subject object at the same time, notifying all observer objects when the state of the subject object changes, so that they can automatically update themselves. For example, the Text property of a text box is bound to an X data source and automatically synchronizes the value of text when the X data source changes. The Observer maintains a list of observers, notifying them of possible performance issues (such as the list is long, or the logic of the update is time-consuming, etc.).
Viewer interface
publicInterface iwatcher { publicvoid update (String str);}
//"Viewer interface
Public interface " Span style= "color: #000000;" > iwatched { public void Addwatcher (Iwatcher watcher); public void Removewatcher (Iwatcher watcher); public void Notifywatchers (String str);}
The specific observer
publicclassimplements iwatcher { @Override publicvoid Update (String str) { System.out.println (str); }}
//The specific observed person
Public classConcretewatchedImplementsiwatched {Privatelist<iwatcher> watchers =NewArraylist<>(); @Override Public voidAddwatcher (Iwatcher watcher) {Watchers.add (watcher); } @Override Public voidRemovewatcher (Iwatcher watcher) {watchers.remove (watcher); } @Override Public voidnotifywatchers (String str) {
Notify the Viewer
for(Iwatcher iwatcher:watchers) {iwatcher.update (str); } }}
PackageObserverpattern; Public classMain { Public Static voidExecuteobserverpattern () {System.out.println ("Observer Pattern:"); Iwatched watched=Newconcretewatched (); Iwatcher Watcher1=NewConcretewatcher (); Iwatcher Watcher2=NewConcretewatcher (); Concretewatcher Watcher3=NewConcretewatcher (); Watched.addwatcher (Watcher1); Watched.addwatcher (WATCHER2); Watched.addwatcher (WATCHER3); Watched.notifywatchers ("Hello World!!!"); }}
Design Patterns-behavioral patterns-observer patterns