Observer pattern
Intent: define a one-to-many dependency between objects, and when the state of an object changes, all objects that depend on it are notified and automatically updated.
Workaround: An object state changes to other object notification issues, and to take into account the ease of use and low coupling, to ensure a high degree of collaboration.
use: the state of an object (the target object) is changed, and all dependent objects (Observer objects) are notified of the broadcast notification.
The key: There is a ArrayList in the abstract class that holds the observers.
Advantages: 1, the observer and the observer are abstract coupled.
2, set up a set of trigger mechanism.
Cons: 1, if an observer object has a lot of direct and indirect observers, all observers are notified to spend a lot of time.
2. If there is a cyclic dependency between the observer and the observation target, observing the target triggers a cyclic call between them, which can cause the system to crash.
3. The observer pattern does not have a mechanism for the observer to know how the target object is changing, but only to know that the observation target has changed.
code example:
1. Define the Observer abstract class
/**@author*/publicabstract class Observer { publicabstractvoid update (String msg);}
2. Define multiple observers
Public class extends observer{ @Override publicvoid update (String msg) { // TODO auto-generated Method stub System.out.println (Observer1. Class+ ":" +msg);} }
public class Observer2 extends observer{@Override void update (String msg) {
//
TODO auto-generated method stub System.out. println (Observer2. Class + ":" +msg); }}
Public class extends observer{ @Override publicvoid update (String msg) { // TODO auto-generated Method stub System.out.println (Observer3. Class+ ":" +msg);} }
3. Definition of the person being observed
Importjava.util.ArrayList;Importjava.util.List;/*** Observer mode-the person being observed *@author[email protected] **/ Public classSubject {PrivateList<observer> obs=NewArraylist<observer>(); Public voidAdd (Observer ob) {obs.add (OB); } Public voidsetmsg (String msg) { for(Observer ob:obs) {ob.update (msg); } } Public Static voidMain (string[] args) {Observer1 O1=NewObserver1 (); Observer2 O2=NewObserver2 (); Observer3 O3=NewObserver3 (); Subject s=NewSubject (); S.add (O1); S.add (O2); S.add (O3); S.setmsg (Information); S.setmsg (Change); }}
Java Watcher pattern