[关闭]
@xmruibi 2015-03-19T23:47:45.000000Z 字数 2378 阅读 728

Service Provider Interface

Design_pattern


A service provider framework is a system in which multiple service providers implement a service, and the system makes the implementations available to its clients, decoupling them from the implementations.

There are three essential components of a service provider framework:

The service access API typically allows but does not require the client to specify some criteria for choosing a provider. In the absence of such a specification, the API returns an instance of a default implementation. The service access API is the “flexible static factory” that forms the basis of the service provider framework.

An optional fourth component of a service provider framework is a service provider interface, which providers implement to create instances of their service implementation. In the absence of a service provider interface, implementations are registered by class name and instantiated reflectively (Item 53). In the case of JDBC, Connection plays the part of the service interface, DriverManager.registerDriver is the provider registration API, DriverManager.getConnection is the service access API, and Driver is the service provider interface.

There are numerous variants of the service provider framework pattern. For example, the service access API can return a richer service interface than the one required of the provider, using the Adapter pattern [Gamma95, p. 139]. Here is a simple implementation with a service provider interface and a default provider

  1. public interface Service {
  2. ... // Service-specific methods go here
  3. }
  4. // Service provider interface
  5. public interface Provider {
  6. Service newService();
  7. }
  8. // Noninstantiable class for service registration and access
  9. public class Services {
  10. private Services() { } // Prevents instantiation (Item 4)
  11. // Maps service names to services
  12. private static final Map<String, Provider> providers =
  13. new ConcurrentHashMap<String, Provider>();
  14. public static final String DEFAULT_PROVIDER_NAME = "<def>";
  15. // Provider registration API
  16. public static void registerDefaultProvider(Provider p) {
  17. registerProvider(DEFAULT_PROVIDER_NAME, p);
  18. }
  19. public static void registerProvider(String name, Provider p){
  20. providers.put(name, p);
  21. }
  22. // Service access API
  23. public static Service newInstance() {
  24. return newInstance(DEFAULT_PROVIDER_NAME);
  25. }
  26. public static Service newInstance(String name) {
  27. Provider p = providers.get(name);
  28. if (p == null)
  29. throw new IllegalArgumentException(
  30. "No provider registered with name: " + name);
  31. return p.newService();
  32. }
  33. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注