Some of the basics we need to know about event snooping.
A) The three elements of the event:
SOURCE --event SourceWhen-- event occurrence timemessage-- event subject message, information that you want to pass through the event
b) Event Flow process:
(1) Event source Registration Listener, (2) event occurrence, (3) Notification Listener, (4) Listener processing
So based on the above background knowledge, we come to implement a simple listener, and test the whole process of event monitoring.
A simple and reasonable event vector is designed according to the three elements of the event: event
Public classEventImplementsSerializable {PrivateObject Source; PrivateDate when; PrivateString message; PublicObject GetSource () {returnsource; } Public voidSetSource (Object source) { This. Source =source; } PublicDate Getwhen () {returnWhen ; } Public voidSetwhen (Date when) { This. When =When ; } PublicString getMessage () {returnmessage; } Public voidsetmessage (String message) { This. Message =message; }}
Listener interface: EventListener
Public Interface EventListener { /** * Event triggered @param Events* / void handleevent (Event event);}
Listener implementation: MyListener
Public class Implements EventListener { private log log = Logfactory.getlog (getclass ()); Private New SimpleDateFormat ("Yyyy-mm-dd hh:mm:ss"); @Override publicvoid handleevent (Event event) { log.info ("source : "+ event.getsource () +", message: "+ event.getmessage () +", When: " + Sdf.format (event.getwhen ())); }}
To normalize, here we develop an event source interface: EventSource
Public Interface EventSource { /** * Add listener @param listener */ void AddListener (EventListener listener); /** * Notification listener * /void notifylisteners ();}
Write the event source for the test: MySource
Public classMySourceImplementsEventSource {Privatelist<eventlistener> listeners =NewArraylist<eventlistener>(); Private intvalue; @Override Public voidAddListener (EventListener listener) {Listeners.add (listener); } @Override Public voidnotifylisteners () { for(EventListener listener:listeners) {Event Event=NewEvent (); Event.setsource ( This); Event.setwhen (NewDate ()); Event.setmessage ("SetValue" +value); Listener.handleevent (event); } } Public intGetValue () {returnvalue; } Public voidSetValue (intvalue) { This. Value =value; Notifylistener (); } Public Static voidMain (string[] args) {MySource source=NewMySource (); Source.addlistener (NewMyListener ()); Source.setvalue (100); }}
Test output:
Source [email protected] message SetValue when 2018-05-01 01:18:35
*ps: Does it feel like the observer design pattern, yes. In terms of effect, the event listener pattern and the observer pattern are not different, but there are some differences in the setting of the event model. There is no event role in the observer pattern, or it is merged into the observable role, which is the integration of event sources and events.
Java implements a simple event listener