The definition of the Observer design pattern: Defines a one-to-many dependency between objects, so that when an object changes state, all its dependents are notified and updated automatically.
Object-oriented design principle: work hard to design the loose coupling between interacting objects
In our actual application, we will also encounter one-to-many, or more-to-a situation. One is that a target corresponds to an observer. Many-to-one refers to multiple targets that correspond to one observer.
Benefits of loose coupling:
First, it adapts to the flexibility of change;
Second, when the internal structure and implementation of a service gradually change, do not affect other services
It's class diagram
The observer pattern is still quite extensive in Android applications, such as the listener
public void Setonmenulistonitemclicklistener (Onmenulistonitemclicklistener listener) {Mlistener = listener;} Public interface Onmenulistonitemclicklistener {public void Onselectitem (int groupposition, int childposition);}
Set the listener, as long as the Onselectitem is called, the Observer will know.
Menufragment menufragment = new Menufragment (); Menufragment.setonmenulistonitemclicklistener (this);
In fact, Broadcastreceiver is also used by observers, in practical applications, if a thing changes the need to notify another thing at this time need to use the observer to monitor
The advantages and disadvantages of the observer pattern
Excellent:
1. Achieve loose coupling between observer and observed person
2, support a one-to-many notification, as long as the registered observers can receive notification
Lack:
1, may need to call multiple times can receive all the required data
2, there may be redundant data
Reference book Code: http://download.csdn.net/detail/deng0zhaotai/7921121
Reference book: "Head First design mode"
Viewer mode for Android design mode