Supporting singleton and factory providers

Suppose your service instances cannot be created simply by a constructor. What if you need to reuse instances, maybe to have a singleton provider instance? Or maybe execute some logic whenever a new service instance is created? There is a handy feature of services that lets you create factory methods to get service instances. All you need to do is add a method with the name provide() in your provider classes. The method needs to be a public static method and it shouldn't take any arguments. Also, the return type should be the same as the type of the service being provided. If the ServiceLoader sees this method, it calls it, and uses the return of the method as the service instance. If it doesn't find such a method, it calls the public no-args constructor like we've already seen. This allows you to hook into the provider instance creation step, and here you can execute any necessary code, as well as get an opportunity to create the object that the ServiceLoader will use as the provider instance.

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

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