I mean the "service provider infrastructure" as discussed in Chapter 2 of Effective Java , which seems to be the right way to handle the problem that I encounter when I need to instantiate one of several classes at runtime, based on String to select this service, and a Configuration object (essentially an XML snippet):
But how can I get individual service providers (for example, a bunch of default providers + some custom providers) to register?
interface FooAlgorithm { } interface FooAlgorithmProvider { public FooAlgorithm getAlgorithm(Configuration c); } class FooAlgorithmRegistry { private FooAlgorithmRegistry() {} static private final Map<String, FooAlgorithmProvider> directory = new HashMap<String, FooAlgorithmProvider>(); 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; } }
eg. if I write custom classes MyFooAlgorithm and MyFooAlgorithmProvider to implement FooAlgorithm and I distribute them in the bank, is there any way to get the registerProvider automatically call or my client programs that use the algorithm should explicitly call FooAlgorithmRegistry.registerProvider () for each class they want use?
source share