Defines one-to-multiple dependencies between objects. In this way, when the state of an object changes, all dependent objects will receive notifications and update automatically.
Composition of the observer mode:
Abstract topic role:Saves all references to the observer object in a collection. Abstract topic provides an interface to add and delete observer roles.
Specific topic roles:When the internal status of a specific topic changes, a notification is sent to all registered observers.
Abstract observer role: Defines an interface for all specific observers and updates themselves when receiving notifications of a topic.
Specific observer role:This role implements the update interface required by the abstract observer role, so that its status can be consistent with that of the topic.
Observer mode UML diagram:
Sample Code of observer mode: <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> Vc3Ryb25nPjxicj4KPC9zdHJvbmc + labels = "brush: java;"> public interface Subject {public void addObserver (Observer observer); public void removeObserver (Observer observer ); public void policyobservers (String str );}
ConcreteSubject. Java
Import java. util. ArrayList; public class ConcreteSubject implements Subject {ArrayList
Observers = new ArrayList
(); Public void addObserver (Observer observer) {observers. add (observer);} public void removeObserver (Observer observer) {observers. remove (observer) ;}@ Overridepublic void policyobservers (String str) {// notify all observers for (Observer o: observers) {o. update (str );}}}
Observer Interface Class Observer. Java
public interface Observer {public void update(String str);}
Specific observer class(Multiple implementations can be implemented)ConcreteObserver. Java
Public class ConcreteObserver implements Observer {@ Overridepublic void update (String str) {System. out. println ("notified observer --" "+ str );}}
Test. java
/*** Test observer mode ** @ author neng **/public class Test {public static void main (String [] args) {// as long as it is the observer and topic that implements the interface. many-to-many ConcreteObserver observer1 = new ConcreteObserver (); ConcreteObserver observer2 = new ConcreteObserver (); ConcreteSubject values = new ConcreteSubject (); values (observer1); values ); concretesubject1.policyobservers ("this is a message !!! ! "); ConcreteSubject1.removeObserver (observer2); concretesubject1.policyobservers (" command !! ");}}
Observer mode purpose:
In Android and ios, Notification is implemented in observer mode.
Event listening in Java is also implemented in observer mode.
Communication between multiple objects (one-to-many, many-to-many) can be performed in the Observer mode. The coupling between the subject and the observer is very low and the scalability is very strong!
Reprinted please indicate the source: http://blog.csdn.net/xn4545945