Let’s consider the following simplified Resource hierarchy:
public abstract class Resource {
static public boolean accepts(String resource);
}
public class AudioResource extends Resource {
static public boolean accepts(String resource) {
//Check if we can proceed this resource as audio
//Some complex logic there ...
}
}
public class VideoResource extends Resource {
static public boolean accepts(String resource) {
//Check if we can proceed this resource as video
//Another complex logic there
}
}
Resource has dozens subclasses and number grows. Each sub-resource:
- has some logic to determine if it accepts resource or not. E.g. it may parse resource URL with regexp or something;
- is not singleton by design;
Now, we want to create a factory which iterates through all available subclasses and creates one which accepts resource (checks it using the accepts method).
Something like this (let’s suppose for a moment that Java has static methods polymorphism):
public class ResourceFactory {
private static List<Class<Resource>> registry;
{
//Populate registry once on start
}
public static Resource createResource(String resource) {
for (Class<Resource> clazz : registry) {
if (clazz.accepts(resource))
return clazz.createInstance(resource);
}
}
}
Unfortunately (or not?), Java doesn’t support polymorphic static methods. Considering that, what are the possible ways to design Resource and ResourceFactory?
You could use:
See ServiceLoader for how to register the factories:
http://docs.oracle.com/javase/6/docs/api/java/util/ServiceLoader.html
Note: the code is untested