lundi 24 juillet 2017

Best design pattern to use with Spring

I have a problem that I am trying to solve. I need to be able to return an implementation based on a user's input. I have looked into using the Abstract Factory pattern, but am not sure if it is the best way to go or not (Or if Spring can help me a little along the way).

Here is the interface the factories will be returning:

public interface Flow {
    List<Message> execute(String sessionKey);
}

and 1 implementation of that interface:

@Component("AssignSeatFlow")
public class AssignSeatFlow implements ChatbotFlow {

    private SeatService seatService;

    @Autowired
    public AssignSeatFlow(final SeatService seatService) {
        this.seatService = seatService;
    }

    @Override
    public List<Message> execute(String sessionKey) {
        // Implementation here
    }
}

My current Factory interface:

public interface FlowFactory {

    Flow getFlow(final String intentCode);

}

and its implementation:

@Component
public class FlowFactoryImpl implements FlowFactory {

    @Resource("AssignSeatFlow")
    private Flow assignSeatFlow;

    @Override
    public Flow getFlow(final String intentCode) {
        if(StringUtils.isNullOrEmpty(intentCode)) {
            throw new IllegalArgumentException("Intent Code cannot be empty");
        }

        switch (intentCode.toUpperCase()) {
            case "AssignSeatFlow":
                return assignSeatFlow;
            default:
                throw new IllegalArgumentException("Unable to determine flow");
        }
    }
}

The reason this doesn't seem ideal is that as I add more Flows, the factory will get much larger and I would have to modify it every time I do so. I am also not a fan of field Autowiring as it makes testing more complicated and less explicit.

Thanks for any feedback.

Aucun commentaire:

Enregistrer un commentaire