2
I got the following Factory
. In it I urge a class responsible for parsing the file in question. For this parser to be instantiated, it is first verified in the conditions whether that parser is correct 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 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 Pattern design, since I will have hundreds or even thousands of PARSERS
. I saw in some examples that it would be interesting to put all the PARSERS
in a Collection and implement a statistical method in each PARSER
to check whether the PARSER
in question is what needs to be instantiated. Only there I would come across the need to instantiate the PARSER
before I even use it, 'cause I’d have to use maybe Set<InvoiceParser>
and then set.add(new XXX_PARSER)
and so on, only if I instantiate this way into a Collection I break all my algorithm which is based on the constructor of the Invoiceparser class, which is the parent of all PARSERS.
What would be the best way to refactor this Factory to meet my need?
If you keep a set of the kind
Class<?>
do not need to instantiate the various parsers beforehand. You can even save a map with the class and its regex, and if any of the elements play, instantiate the parser by reflection.– Isac
Which version of Java are you using?
– Felipe Marinho
I am using Java 8
– Gustavo Piucco