Some basics we need to know about event listening.
a) Three elements of the event:
source -- event source when -- the time when the event occurred message -- the event topic message, that is, the 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, let's implement a simple listener and test the complete process of event monitoring.
Design a simple and reasonable event carrier according to the three elements of the event: Event
public class Event implements Serializable { private Object source; private Date when; private String message; public Object getSource() { return source; } public void setSource(Object source) { this.source = source; } public Date getWhen() { return when; } public void setWhen(Date when) { this.when = when; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
Listener interface: EventListener
public interface EventListener { void handleEvent(Event event); }
Listener implementation: MyListener
public class MyListener implements EventListener { private Log log = LogFactory.getLog(getClass()); private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); @Override public void handleEvent(Event event) { log.info("source: " + event.getSource() + ", message: " + event.getMessage() + ", when: " + sdf.format(event.getWhen())); } }
In order to standardize, we formulate an event source interface here: EventSource
public interface EventSource { void registerListener(EventListener listener); void notifyListener(); }
Event source for writing tests: MySource
public class MySource implements EventSource { private EventListener listener; private int value; @Override public void registerListener(EventListener listener) { this.listener = listener; } @Override public void notifyListener() { if (listener == null) return; Event event = new Event(); event.setSource(this); event.setWhen(new Date()); event.setMessage("setValue " + value); listener.handleEvent(event); } public int getValue() { return value; } public void setValue(int value) { this.value = value; notifyListener(); } public static void main(String[] args) { MySource source = new MySource(); MyListener listener = new MyListener(); source.registerListener(listener); source.setValue(100); } }
Test output:
[INFO]-[MyListener-handleEvent(16)]: source: com.lichmama.event.MySource@2019a9d1, message: setValue 100, when: 2018-05-01 01:18:35