First, the callback function
Why is the callback function first? Because this is the key to understanding the listener, the Observer pattern.
What is a callback function
Called callbacks, Functions for callbacks. A callback function is just a functional fragment, a function implemented by the user in accordance with the callback function calling convention. There is a popular definition: programmer a wrote a program (program a), which reserved a callback function interface, and encapsulated the program. Programmer B wants A to invoke a method in its own program B, so he callbacks his method in B through the interface in a.
As an example:
There are two entities: Callback abstract interface, callback person (i.e. program a)
Callback Interface (Icallback)
Public Interface Icallback { publicvoid callBack ();}
The callback (the class used to invoke the callback function)
Public class Caller { publicvoid call (Icallback callBack) { System.out.println (" Start ... "); Callback.callback (); System.out.println ("End ...");} }
Callback Test:
Public Static void Main (string[] args) { new Caller (); Call.call (new icallback () { @Override publicvoid CallBack () { System.out.println ("Finally the callback succeeded!") "); } });}
Console output:
Start ... Finally the callback succeeded! End ...
There's another way.
New Icallback () { @Override publicvoid callBack () { System.out.println ( "Finally the callback succeeded!" "); } }; Call.call (CALLBACKB);
or implement this Icallback interface class
class Implements icallback{ @Override publicvoid callBack () { System.out.println ("Finally the callback succeeded!") "); }}
There is no way to find this model and execute a thread, like thread. Yes, thread is the callback, and Runnable is a callback interface.
New Thread (new Runnable () { @Override publicvoid run () { System.out.println ("Callback a new thread! "); }}). Start ();
Callable is also a callback interface, the original has been used. And then we start talking about the event listener.
Second, the event monitoring mode
What is Event listener
Listeners will listen to events of interest to them once the event has been triggered or changed, immediately notified and responded. For example, the button event in an Android program.
The Java event Monitoring mechanism can be summarized as 3 points:
- Java's event monitoring mechanism involves event source, event listener, event object Three components, listener is generally an interface, used to contract the invocation method.
- When an action occurs on the event source object, it invokes a method of the event listener and passes the event object past when the method is called.
- The event listener implementation class, usually written by the developer, is used by the event object to get the event source to process the action on the event source.
As an example,
Here I for convenience, direct use Jdk,eventlistener listener, interested can go to study under source code, very simple.
Listener interface
Public Interface extends Java.util.EventListener { // event handling public void Handleevent (EventObject event);}
Event Object
Public class extends java.util.eventobject{ privatestaticfinallong serialversionuid = 1L; Public EventObject (Object source) { Super(source); } Public void doevent () { System.out.println(this. GetSource ());} }
Event Source
The event source is the entry for the event object, including the listener's registration, revocation, notification
Public classEventSource {//Listener list, register the listener to join this list PrivateVector<eventlistener> ListenerList =NewVector<eventlistener>(); //Register Listener Public voidAddListener (EventListener eventlistener) {listenerlist.add (EventListener); } //Revoke Registration Public voidRemoveListener (EventListener eventlistener) {listenerlist.remove (EventListener); } //Accept External Events Public voidnotifylistenerevents (EventObject event) { for(EventListener eventlistener:listenerlist) {eventlistener.handleevent (event); } }}
Test execution
Public Static voidMain (string[] args) {EventSource EventSource=NewEventSource (); Eventsource.addlistener (NewEventListener () {@Override Public voidhandleevent (EventObject event) {event.doevent (); if(Event.getsource (). Equals ("Closewindows") {System.out.println ("Doclose"); } } }); /** Incoming OpenWindows event, notify Listener, Event listener, listener interested in open event will be executed **/eventsource.notifylistenerevents (NewEventObject ("OpenWindows"));}
Console display:
Notifies an event source Source:openwindows notifies an event source Source:openwindowsdoopen something ...
Here you should know very well what is the event listener mode. So where is the callback interface, where is the callback, right! EventListener is a callback interface class, Handleevent is a callback function interface, through the callback model, EventSource event source can callback specific listener actions.
With this understanding, there are some changes that can be made here. Provides specific attention methods and event triggers for specific events
Public classEventSource {... Public voidonclosewindows (EventListener eventlistener) {System.out.println ("Focus on closing window events"); Listenerlist.add (EventListener); } Public voiddoclosewindows () { This. notifylistenerevents (NewEventObject ("Closewindows")); } ...} Public Static voidMain (string[] args) {EventSource Windows=NewEventSource (); /*** Another way to achieve*/ //focus on closing events, implementing callback interfacesWindows.onclosewindows (NewEventListener () {@Override Public voidhandleevent (EventObject event) {event.doevent (); if(Event.getsource (). Equals ("Closewindows") {System.out.println ("Focus on closing the window event via Onclosewindows: and execute success. Closewindows "); } } }); //window Close Actionwindows.doclosewindows ();}
This is similar to our window program, the button listener. We can also customize the listener for clicking and double-clicking events.
Third, the Observer pattern
What is Observer mode
The observer pattern is essentially the same as the listener, and the key to use is figuring out what the observer is and what is being observed.
- The Observer (Observer) is the equivalent of an event monitor. There is a microblogging model better understand, a user focus on B users, then A is the observer of B, B is an observer, once B has made any comments, a can be obtained.
- The Observer (Observable) is equivalent to the event source and event, and when the event source notification logic is executed, the callback method update for observer is called back.
As an example,
For convenience, I also use the Observer that comes with the JDK directly.
An observer
Public class Implements Observer { @Override publicvoid update (Observable o, Object Arg) { If(arg.tostring (). Equals ("OpenWindows")) { System.out.println ("opened window"); } }}
The person being observed
Observable is an observer of the JDK, and it is possible to look at the source code similar to the previous listener event source.
The main methods are:
- Addobserver () Adds an observer, similar to listener mode.
- Notifyobservers () notifies all observers.
The implementation description of the class Watched.java: The Observer, the event source and event object that corresponds to the event listener. Also understood as the object of the subscription main duties: REGISTER/REVOKE Observer (listener), receive Subject Object (Event object) to the Observer (listener), specifically by the Observer (listener) interested in the execution
/*** * Class Watched.java Implementation Description: The Observer, equivalent to the event listener events source and event object. Also understood as subscribed objects * Primary duties: REGISTER/REVOKE Observer (listener), receive Subject Object (Event object) to the Observer (listener), executed by an interested observer (listener)@authorXUAN.LX November 22, 2016 afternoon 3:52:11*/ Public classWatchedextendsObservable { Public voidnotifyobservers (Object Arg) {/*** In order to avoid concurrency conflicts, set the changed flag bit changed =true, the current thread can notify all observers, the internal synchronization block will be set to false, the notification process, is newly registered and revoked cannot be notified. */ Super. setchanged (); /*** Event Trigger, notify all interested observers*/ Super. Notifyobservers (ARG); }}
Test execution
Public Static voidMain (string[] args) {watched watched=Newwatched (); Watcherdemo Watcherdemo=NewWatcherdemo (); Watched.addobserver (Watcherdemo); Watched.addobserver (NewObserver () {@Override Public voidUpdate (Observable o, Object Arg) {if(Arg.tostring (). Equals ("Closewindows") {System.out.println ("Closed Window"); } } }); //triggers an open window event to notify the ObserverWatched.notifyobservers ("OpenWindows"); //triggers a close window event to notify the ObserverWatched.notifyobservers ("Closewindows");}
Console output:
Already open window has closed window
Summarize
From the entire implementation and invocation process, the observer and listener patterns are basically the same.
Interested you can implement a simple micro-boga focus and cancellation function based on this model. In the final analysis, it is the event-driven model that decouples the caller and callee through a list, callback function, and is independent of each other.
The whole design pattern is designed to be low-coupling, low-dependency.
Further, what is a model for message middleware? Decouple the producer + Service Center (event source) and consumer (listener) from Message Queuing. Message this corresponds to a specific event object, just stored in a team joins (with the function of a peak-shaving), and the service center callbacks the consumer interface by pulling or fetching the model response. Presumably based on this model, it is also possible to implement a simple message middleware.
Also such as guava listenablefuture, the use of listener mode to solve the Future.get () has been blocked waiting to return the results of the problem.
Interested students, you can think about the relationship between the observer and the chain of responsibility, I see.
There is also a linked list, which the observer notifies all observers, the observer handles independently, and the observer does not affect each other. And the chain of responsibility, pay attention to the drum transmission, that is, each node only records the successor node, from the current node to decide whether to pass down. Commonly used in workflows, filter Web filters.
Transferred from: https://my.oschina.net/u/923324/blog/792857
Java Design pattern Supplement: Callback mode, event listener mode, observer mode (GO)