In fact, the truth is very simple.
[Listener]
I want to listen to something, so I must have a listener/or an observer.Myobserver.
There is a method in my listener to process the listened data.Update ().
So:
(1) What are the requirements of listener and method? That is, the interface provided by the listener must be implemented.Observer
(2) How can I register this listener with the listener? There are many methods. For example, the listener provides a singleton Class C, which allows the caller to call C. getinstance (). setlistener (ourlistener );Add
[Listener]
The listener usually maintains a list <listener>. After a Dongdong changes, it notifies all listeners (for () to call listener cyclically. method (), so the listener is implemented.
[Just talk about it]
The listened party can use its own thread to notify all listeners, or call its own thread pool for processing.
I personally prefer the latter, because ifProgramComplicated: the thread pool of the listener itself can be asynchronously used to free the listener thread.
The listener can either be new or bean assembled. It doesn't matter.
[Program appearance]
[1] Subject interface observer
Class observer {
Notify ();
}
[2] caller myobserver
Class mylistener {
Observer listener = new myobserver ();// New and assembled
PublicVoid dobizoperation (){
}
Class myobserver implements observer {
Notify (){
}
}
}
[3] called Subject
Class subject {
List <interfacebycalled> listeners = new list <interfacebycalled> ();
PublicVoid setlistener (interfacebycalled listener ){
Listeners.Add(Listener );
}
PublicList <observer> informlisteners (){
For(Observer listener: This. Listeners ){
Listener. Policy ();
}
}
}
[4] At last, inject mylistener into subject.
Observer observer = mylistener. getlistener ();
Subject. setlistener (observer );