Example

Look at the sample code at 09-module-patterns/04-optional-dependencies-with-services.We have two modules, pattern.four and pattern.four.optlib. We want pattern.four to optionally depend on pattern.four.optlib using the services pattern we've seen so far.

The module pattern.four contains a service type LibInterface that it exports. It also declares that it uses provider implementations of LibInterface, which is what essentially makes LibInterface a service type:

    module pattern.four { 
      exports pattern.four.external; 
      uses pattern.four.external.LibInterface; 
    } 

The module pattern.four.optlib provides an implementation of the LibInterface service type. It also depends on pattern.four to access the service type in the first place. This is the seemingly inverted relationship we discussed earlier:

    module pattern.four.optlib { 
      requires pattern.four; 
      provides pattern.four.external.LibInterface with 
pattern.four.lib.LibImpl; }

There's a class LibImpl in pattern.four.optlib that implements LibInterface as declared in the preceding module definition:

    public class LibImpl implements LibInterface { 
      public void publicApi() { 
        System.out.println("Called API method in Service"); 
      } 
    } 

The module pattern.four is now totally unaware of pattern.four.optlib. It uses the ServiceLoader API to get any available instances, and if the optional module is available, it's happy to use it:

    public class Util { 
      public void utilMethod() { 
        Iterable<LibInterface> libInstances =
ServiceLoader.load(LibInterface.class); for (LibInterface libInstance : libInstances) { libInstance.publicApi(); } } }

Benefits:

  • Extends the plug-and-play concept that the previous pattern solved and adds a new level of decoupling. Modules can be optional both at compile time and runtime!
  • Extends the one-to-one dependency of requires static with the services providing one-to-many dependency. There could be multiple modules providing services that are optionally picked up by the module using the services.
..................Content has been hidden....................

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