Implementing the Service Consumer
The class AdviceConsumer implements a simple service consumer for the IAdvice service in the package org.advice.serviceconsumer of the serviceconsumer module (Example 19.6).
The code at (1) shows how advice for the UK locale is obtained via the org.advice .servicelocator.AdviceLocator class in the servicelocator module. The static method getAdvice() of the AdviceLocator class at (2) returns an Optional<IAdvice> object. This object can be queried to extract the advice at (3) with the getContent() method, if there is one. Otherwise, the orElse() method at (4) provides an appropriate message.
The code at (5) shows how all advice providers for the IAdvice service can be obtained via the AdviceLocator class. The static method getAllAdvice() of the AdviceLocator class at (6) returns a List<IAdvice> object with all providers for this service. A stream on this list is used at (7) to print the advice from each provider by extracting the advice with the getContent() method.
Example 19.6 Implementing of the Advice Service Consumer
// File: ./src/serviceconsumer/org/advice/serviceconsumer/AdviceConsumer.java
package org.advice.serviceconsumer;
import java.util.*;
import org.advice.servicelocator.*;
import org.advice.si.*;
public class AdviceConsumer {
public static void main(String[] args) {
// Get advice for the UK locale. // (1)
Optional<IAdvice> optAdvice = AdviceLocator.getAdvice(Locale.UK); // (2)
String adviceStr = optAdvice.map(IAdvice::getContent) // (3)
.orElse(“Sorry. No Advice!”); // (4)
System.out.println(“Advice for UK locale: ” + adviceStr);
// Get all implemented advice. // (5)
System.out.println(“Printing all advice:”);
List<IAdvice> allAdvice = AdviceLocator.getAllAdvice(); // (6)
allAdvice.stream() // (7)
.forEach(a -> System.out.println(a.getContent()));
}
}
The serviceconsumer module (Figure 19.15(a)) only requires the module that declares the service, as shown at (1), and the module that can locate service providers for this service as at (2). Note that the consumer module does not directly depend on any service providers.
// File: ./src/serviceconsumer/module-info.java
module serviceconsumer {
requires serviceinterface; // (1)
requires servicelocator; // (2)
}
Leave a Reply