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.

public interface OnCompleteListener {
	public void onComplete();
}

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.

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

ListenerDemo.java, this is a demo of how the listner is being used.

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

Search within Codexpedia

Custom Search

Search the entire web

Custom Search