Sep 102011
 

You’ve seen the Observer Pattern where subscriber get notified from publisher about events when something happened. It’s about the Listener/ Observer, how about another famous pattern named “Callback Pattern”?

What is Callback Pattern?

I can tell you that there’s some similarity about the notification, but the Callback Pattern is very much “Architectural Pattern” and only these diagram and definition can help you to distinguish.

image thumb20 Callback Pattern with RMI Client Callback

Callback Pattern is an Architectural Pattern that allows a client to register with a server for extended operations. This enables the server to notify the client when the operation has been completed.

image thumb21 Callback Pattern with RMI Client Callback

What can Callback Pattern help you?

Use the Callback pattern for a client-server system with time-consuming client operations, and when one or both of the following are true:

  • You want to conserve server resources for active communication.
  • The client can and should continue work until the information becomes available. This can be accomplished with simple threading in the client.
Callback Pattern Example

This Design Pattern is an architectural pattern and needs a server/client application to apply, so I will use the same example in my previous post about Proxy Pattern using RMI for the demo. To save your time, I won’t tell the story again but you should read and run the RMI example first before taking the next step.

First, I will define a BankClientCallback interface, which will act as a standardized channel for the server to interact with the client.

package net.searchdaily.java.design.pattern.callback;

import java.rmi.Remote;
import java.rmi.RemoteException;
/**
 * Callback Pattern with RMI tutorial by http://java.searchdaily.net
 * 
 * @author namnvhue
 * 
 */
public interface BankClientCallback extends Remote {
	public void notifyAction(String action) throws RemoteException;
}

As you can see to allow the server to interact with the client, the client’s now actually a server, so it’s much like server-to-server conversation. Next is for the Server interface

Continue reading »