I have the following Factory
. In it I instantiate a class responsible for parsing the file in question. In order to instantiate this parser, it is first checked under the conditions if that parser is the correct one to perform the processing.
public class InvoiceParserFactory
{
public static InvoiceParser getParser(InvoicePdfReader reader)
{
String invoiceText = reader.getText();
if (isXxxParser(invoiceText)) {
return new XXX_PARSER(invoiceText);
}
else if (isYyyParser(invoiceText)) {
return new YYY_PARSER(invoiceText);
}
else {
throw new InvoiceException("Can't find parser.");
}
}
private static boolean is_XXX_PARSER(String invoiceText) {
Pattern p = Pattern.compile("xxx_regex");
Matcher m = p.matcher(invoiceText);
//as condições aqui são diferentes, portanto não da pra simplificar esses métodos
}
private static boolean is_YYY_PARSER(String invoiceText) {
Pattern p = Pattern.compile("yyy_regex");
Matcher m = p.matcher(invoiceText);
//as condições aqui são diferentes, portanto não da pra simplificar esses métodos
}
}
Here is an example of a PARSER
:
public final class XXX_PARSER extends InvoiceParser
{
@Override
protected void parseSomeText() {
//implementação
}
}
This logic does not scale in this design pattern, since I will have hundreds or even thousands of PARSERS
. I have seen in some examples that it would be interesting to put all PARSERS
into a collection and implement a static method on each PARSER
to check if the PARSER
in question is what needs to be instantiated. But I would have to instantiate PARSER
before I even use it, because I would have to use Set<InvoiceParser>
and then set.add(new XXX_PARSER)
and so on, except that if I instantiate this way in a collection I I break my entire algorithm which is based on the InvoiceParser class constructor, which is the parent of all PARSERS.
What would be the best way to refactor this Factory to meet my needs?