Java Reference
In-Depth Information
Listing 16.1
CalculatorService
interface
[...]
public interface
CalculatorService {
public double
[] parseUserInput(String str)
throws NumberFormatException;
B
C
public double
add(
double
... numbers);
D
public double
multiply(
double
... numbers);
E
public void
printResult(
double
result);
}
The interface defines the four methods we want to implement in our service. The first
one
B
parses a line of user input. The user is supposed to input several numbers sep-
arated by spaces, and this method parses the input as numbers. The
add
method
C
sums all the given numbers and returns the result. There is also a
multiply
method
D
, which multiplies numbers and returns the result. The
printResult
method
E
prints a given result number.
As we already discussed, every
OSG
i service exposes a certain interface to other ser-
vices. Your services
must
provide an interface and implement it.
Listing 16.2 contains the implementation of the interface in listing 16.1.
Listing 16.2
Implementation of
CalculatorService
interface
[...]
public class
CalculatorImpl
implements
CalculatorService {
public double
add(double... numbers) {
double
result = 0;
for
(
double
number:numbers)
result+=number;
return
result;
}
public double
multiply(
double
... numbers) {
double
result = 1;
for
(
double
number:numbers)
result*=number;
return
result;
}
public double
[] parseUserInput(String str)
throws
NumberFormatException {
String[] numbers = str.split(" ");
doubl
e[] result =
new double
[numbers.length];
for
(int i=0;i<numbers.length;i++) {
result[i] = Double.parseDouble(numbers[i]);
}
return
result;
}