Service interface provider lookup

The lookup logic to get service instances is now in the Main classes in both the packt.addressbook and packt.addressbook.ui modules. This is less than ideal. We don't want to repeat the lookup logic in multiple places. One way to solve this is to move the logic to a common place that's accessible by all the consumers of the service. Now, what's the module that's shared by every consumer of the service? It's the module that exports the interface. Wouldn't it be a great idea to move the dependency lookup logic and tuck it away as a default method in the interface? Then none of the consumer modules would need to mess with the ServiceLoader APIs directly. They would just have to call the right interface method to look up the instances.

Let's create two new methods on the SortUtil interface. One to get all service provider instances, and the second to get single instances based on the size of the list (which is a criterion that affects which instance is picked, like we've already seen).

Here are the two new static methods on SortUtil:

    public static Iterable<SortUtil> getAllProviders() { 
      return ServiceLoader.load(SortUtil.class); 
    } 
 
    public static SortUtil getProviderInstance(int listSize) { 
      Iterable<SortUtil> sortUtils =
ServiceLoader.load(SortUtil.class); for (SortUtil sortUtil : sortUtils) { if (listSize < sortUtil.getIdealMaxInputLength()) { return sortUtil; } } return null; }

Here we are returning null if no service instances that matched our requirement were found. This could easily be enhanced to provide a default service in case a suitable instance wasn't found.

Now, Main doesn't have to talk to ServiceLoader and loop through instances anymore:

    SortUtil sortUtil = SortUtil.getProviderInstance(contacts.size()); 
    sortUtil.sortList(contacts); 

I hope you'll agree that the consumption of the service has become much simpler now.

One other change you'll have to do is to move the  uses clause from the packt.addressbook and packt.addressbook.ui modules to the packt.sortutil module. That's because the service is consumed and the ServiceLoader APIs are invoked from the packt.sortutil module now:

    module packt.sortutil { 
      exports packt.util; 
      uses packt.util.SortUtil; 
    } 

Compiling and running the code should give you the same output as before. But this time, the service lookup logic is now refactored into a common module usable by all consumers.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.144.229