Observer pattern: Defines a one-to-many dependency between objects. When the state of an object changes, all objects that depend on it are notified and automatically updated.
A simple example: for example, there are two people Zhang San and John Doe subscribed to weather messages from the meteorological observatory.
1 Public classSubject2 {3 PrivateList<observer> observers =NewArraylist<observer>();4 5 Public voidAttach (Observer Observer)6 {7 OBSERVERS.ADD (Observer);8Observer.update ( This);9 }Ten One Public voidDetach (Observer Observer) A { - OBSERVERS.REMOVE (Observer); - } the - protected voidnotifyobservers () - { - for(Observer observer:observers) + { -Observer.update ( This); + } A } at } - - Public InterfaceObserver - { - Public voidUpdate (Subject Subject); - } in - Public classConcreteSubjectextendsSubject to { + PrivateString subjectstate; - the PublicString getsubjectstate () * { $ returnsubjectstate;Panax Notoginseng } - the Public voidsetsubjectstate (String subjectstate) + { A This. subjectstate =subjectstate; the This. Notifyobservers (); + } - } $ $ Import Staticjava.lang.System.out; - Public classConcreteobserverImplementsObserver - { the PrivateString observerstate; - Wuyi Public voidUpdate (Subject Subject) the { -Observerstate =((ConcreteSubject) subject). Getsubjectstate (); Wu } - About Public voidinfo () $ { -Out.println ("I am:" +observername); -Out.println ("Info:" +observerstate); - out.println (); A } + the PrivateString Observername; - $ Public voidsetobservername (String observername) the { the This. Observername =Observername; the } the } - in Public classClient the { the Public Static voidMain (string[] args) About { theConcreteSubject Weathersubject =NewConcreteSubject (); theWeathersubject.setsubjectstate ("Sunny, 25°"); the +Concreteobserver Zhangsan =Newconcreteobserver (); -Zhangsan.setobservername ("Zhang San"); the BayiConcreteobserver Lisi =Newconcreteobserver (); theLisi.setobservername ("John Doe"); the - Weathersubject.attach (Zhangsan); - Weathersubject.attach (Lisi); the the zhangsan.info (); the lisi.info (); the - Weathersubject.detach (Zhangsan); theWeathersubject.setsubjectstate ("Cloudy, 20°"); the the zhangsan.info ();94 lisi.info (); the } the } the 98 I am: Zhang San AboutInfo: Sunny, 25° - 101 I am: John Doe102Info: Sunny, 25°103 104 I am: Zhang San theInfo: Sunny, 25°106 107 I am: John Doe108Info: Cloudy, 20°
The observer pattern for Java design patterns