If you are unfamiliar with RMI, I recommend jGuru's "Fundamentals of RMI" course. If you are unfamiliar with design patterns or the specifics of the Adapter pattern, I recommend Design Patterns: Elements of Reusable Object-Oriented Software, by Erich Gamma, et al. Online tutorials are also available on the Patterns homepage. (See Resources for links to these materials.)
Initially, you must use RMI's protocol for making remote method calls. It would be beneficial, however, if most of your source code could keep using its existing protocol. The Adapter design pattern solves that problem by providing access to an object through a protocol that that object does not directly support. In this case, you should create adapter classes that wrap up the RMI protocol; this lets your existing code use a local protocol when making a method call on a remote object. Since an adapter class wraps up another object, it is frequently referred to as a wrapper class.
The example application for this article has a class called StatisticsCalculator that performs statistical calculations. Given a Vector of numbers, StatisticsCalculator provides methods that calculate statistical values like standard deviation, median, mode, and mean. A snippet of the code
is shown in Listing 1. (See Resources for the complete source code.)
public class StatisticsCalculator
{
private Vector values_;
public void setValues(Vector values)
{
values_ = values;
}
public double getStandardDeviation()
{
if ((values_ == null) || (values_.size() <= 1))
return 0;
.
.
.
}
}
Listing 1. The StatisticsCalculator class
A typical usage of the StatisticsCalculator class is shown in Listing 2.
StatisticsCalculator sc = new StatisticsCalculator();
Vector v = new Vector();
v.addElement(new Double(100));
v.addElement(new Double(200));
v.addElement(new Double(300));
sc.setValues(v);
System.out.println("Std Dev: " + sc.getStandardDeviation());
Listing 2. Client usage of a local StatisticsCalculator
If you run the StatisticsCalculator object on another system, the easiest way to access it on that remote system is with RMI. By following the standard steps
for RMI support, you can create an interface that extends java.rmi.Remote. Let's call it RemoteStatisticsCalculatorService; it is shown in Listing 3.