Java listener pattern example
Listener pattern is used to perform some task after certain event has happened. It gives you the freedom to define the task to be performed before the event has happened and you can define different tasks in different scenarios for the same event. In this example, the event is the LongRunningTask has finished it’s execution and the task to be performed after this event is to print a message.
OnCompleteListener.java, this listener interface enforces the onComplete method for defineing the task to be performed when it is invoked.
[code language=”java”]
public interface OnCompleteListener {
public void onComplete();
}
[/code]
LongRunningTask.java, this long running task class for demo purposes, it just sleeps for 5 seconds and then invoke the onComplete method on the listener. A real task could be downloading resources.
[code language=”java”]
public class LongRunningTask implements Runnable {
private OnCompleteListener onCompleteListener;
public void setOnCompleteListener(OnCompleteListener onCompleteListener) {
this.onCompleteListener = onCompleteListener;
}
@Override
public void run() {
try {
Thread.sleep(5*1000); // sleep for 5 seconds and pretend to be working
onCompleteListener.onComplete();
} catch (Exception e) {
System.out.print(e.getMessage());
}
}
}
[/code]
ListenerDemo.java, this is a demo of how the listner is being used.
[code language=”java”]
public class ListenerDemo {
public static void main(String args[]) {
LongRunningTask longRunningTask = new LongRunningTask();
longRunningTask.setOnCompleteListener(new OnCompleteListener() {
@Override
public void onComplete() {
System.out.println("Yeah, the long running task has been completed!");
}
});
System.out.println("Starting the long running task.");
longRunningTask.run();
}
}
[/code]
Search within Codexpedia
Search the entire web