Observer pattern
Defines a one-to-many dependency that allows multiple observers to listen to a Subject object at the same time. This subject object notifies all observer objects when the state changes, enabling them to update the status automatically
Subject
PackageCom.hml.observer;Importjava.util.ArrayList;Importjava.util.List; Public classSubject {List<Observer> observers =NewArraylist<observer>(); Public voidaddobserver (Observer o) {observers.add (o); } Public voiddeleteobserver (Observer o) {observers.remove (o); } Public voidNotifychange () { for(Observer o:observers) {o.update (); } }}
Observer
Package Com.hml.observer; Public Interface Observer { publicvoid update ();}
Concreateobservera
Package Com.hml.observer; Public class Implements Observer { publicvoid update () { System.out.println ("A Update ");} }
Concreateobserverb
Package Com.hml.observer; Public class Implements Observer { publicvoid update () { System.out.println ("B update"); }}
Test
Package Com.hml.observer; Public class Test { publicstaticvoid main (string[] args) { new Subject (); Subject.addobserver (new Concreateobservera ()); Subject.addobserver (new Concreateobserverb ()); Subject.notifychange (); }}
Class diagram
One of the bad side effects of splitting a system into a series of collaborative classes is the need to maintain consistency among related objects. We do not want to keep the classes tightly coupled to maintain consistency, which can be inconvenient for maintenance, expansion, and reuse. The key to the observer pattern is the subject subject and the Observer observer, a subject can be a number of people depending on its observer, once the subject state has changed, all observer can be notified. Subject notification does not need to know who is his observer, that is, who the specific observer is, he does not need to know at all. Nor does any particular observer know or need to know the existence of other observers. Therefore, the observer pattern can be used when the change of an object requires changing other objects at the same time.
The observer pattern of the design pattern