I've read this topic with the instruction about how to use factory pattern
factory pattern dynamic approach
I have this in my factory
public class FilterFactory {
static Map<String, Class> creators;
static {
creators = new HashMap<>();
}
/*...*/
}
And this is one of the classes, which I want to put in the factory
public class ExtentionFilterSerializer implements FilterSerializer {
static {
FilterFactory.creators.put(".", ExtentionFilterSerializer.class);
}
/*...*/
}
When I try to use factory in the program, I see that Map is empty. What did I do wrong?
For code related:
The static block to register your class ExtentionFilterSerializer
will execute if only if this unit ExtentionFilterSerializer
is realized on classpath. If you haven't used this class ExtentionFilterSerializer
anywhere in your program, this class wont be loaded, hence the static registration.
Adding a Class.forname("ExtentionFilterSerializer")
to your client application will fix the load issue.
Regarding approach used:
The objective of using a Factory pattern is to determine and create an instance of concrete object type especially when the application cannot determine that at compile time. By adding a static initializer to dynamically register your concrete class, your Factory know of its existence, but still cannot determine which concrete class to use.
Besides, the registration part FilterFactory.creators.put(".", ExtentionFilterSerializer.class);
should never be in ExtentionFilterSerializer
, but in a client program.
Another variant of a Factory design pattern makes the creation method abstract (not same as AbstractFactory pattern). A concrete object can be created using those concrete Factory classes, which looks close to your case. Read this.