title: Simple Java "Service Provider frameworks"?
body: <p>I refer to "service provider framework" as discussed in <a href="http://books.google.com/books?id=ka2VUBqHiWkC&amp;pg=PA8" rel="nofollow noreferrer">Chapter 2 of Effective Java</a>, which seems like exactly the right way to handle a problem I am having, where I need to instantiate one of several classes at runtime, based on a <code>String</code> to select which service, and an <code>Configuration</code> object (essentially an XML snippet):</p>
  
  <p>But how do I get the individual service providers (e.g. a bunch of default providers + some custom providers) to register themselves?</p>
  
  <pre><code> interface FooAlgorithm
   {
       /* methods particular to this class of algorithms */
   }
  
   interface FooAlgorithmProvider
   {
       public FooAlgorithm getAlgorithm(Configuration c);
   }
  
   class FooAlgorithmRegistry
   {
       private FooAlgorithmRegistry() {}
       static private final Map&lt;String, FooAlgorithmProvider&gt; directory =
          new HashMap&lt;String, FooAlgorithmProvider&gt;();
       static public FooAlgorithmProvider getProvider(String name)
       {
           return directory.get(serviceName);
       }
       static public boolean registerProvider(String name, 
           FooAlgorithmProvider provider)
       {
           if (directory.containsKey(name))
              return false;
           directory.put(name, provider);
           return true;
       }
   }
  </code></pre>
  
  <p>e.g. if I write custom classes MyFooAlgorithm and MyFooAlgorithmProvider to implement FooAlgorithm, and I distribute them in a jar, is there any way to get registerProvider to be called automatically, or will my client programs that use the algorithm have to explicitly call FooAlgorithmRegistry.registerProvider() for each class they want to use?</p>