mercredi 13 juin 2018

Which pattern or method to use when calling a regex check method in multiple if statements?

I created a factory pattern in my class.

In this class I injected classes which implements Command interface based on incoming String parameter.

Factory class

@Component
@RequiredArgsConstructor
public class CommandFactory {
    private final ACommand aCommand;
    private final BCommand bCommand;
    private final CCommand cCommand;
    private final DCommand dCommand;
    private final ECommand eCommand;
    private final FCommand fCommand;

    public Command createCommand(String content) {
        if (aCommand.isMatching(content)) {
            return aCommand;
        } else if (bCommand.isMatching(content)) {
            return bCommand;
        } else if (cCommand.isMatching(content)) {
            return cCommand;
        } else if (dCommand.isMatching(content)) {
            return dCommand;
        } else if (eCommand.isMatching(content)) {
            return eCommand;
        } else if (fCommand.isMatching(content)) {
            return fCommand;
        } else {
            return null;
        }
    }

In isMatching() method there are different regex'es and I try to figure out how this incoming String should be processed.

I am looking for a cleaner way to get rid of these sequential if statements. Because whenever I create a new class into this factory I add another if statement.

Aucun commentaire:

Enregistrer un commentaire