Observer mode (listener, listener)

Source: Internet
Author: User

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 );

 

 

 
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.