How to implement factory pattern with dagger using annotation

Viewed 98

What I have done currently is

Created an abstract class

public interface AbstractRawPathStrategy {
    String getRouteKey();

    void processRequest();
}

Implemented the classes

public class GetDocumentImpl implements AbstractRawPathStrategy {
    @Override
    public String getRouteKey() {
        return "GET_DOCUMENT";
    }

    @Override
    public void processRequest() {
        log.info("Inside get document");
    }
}

Created a routing factory

public class RawPathStrategyFactory {
    private final Map<String, AbstractRawPathStrategy> dictionary;

    @Inject
    public RawPathStrategyFactory(final Set<AbstractRawPathStrategy> abstractRawPathStrategySet) {
        dictionary = new HashMap<>();
        for (AbstractRawPathStrategy abstractRawPathStrategy : abstractRawPathStrategySet) {
            dictionary.put(abstractRawPathStrategy.getRouteKey(), abstractRawPathStrategy);
        }
    }

   
    public AbstractRawPathStrategy getByRouteKey(final String rawPath) {
        return dictionary.get(rawPath);
    }
}

Instantiated the factory

@Module
public class AppModule {
    @Provides
    @Singleton
    public RawPathStrategyFactory getRouteKeyStrategyFactory() {
        Set<AbstractRawPathStrategy> abstractRouteKeyStrategies = new HashSet<>();
        abstractRouteKeyStrategies.add(new GetDocumentImpl());
        abstractRouteKeyStrategies.add(new GetUserRightsImpl());
        return new RawPathStrategyFactory(abstractRouteKeyStrategies);
    }

What I want is to go to respective class based on the route key (String). How can this be done without instantiating each class with new in AppModule. Any cleaner way to do this?

2 Answers

The easy, boring, way would be to use some static identifier which you'll have to set for each distinct subtype of your abstract class, and subsequent subtype thereof.

The more complicated, albeit fun, way to do this would be to use reflection.

Related