Chris311
Chris311

Reputation: 3992

Purpose of the injection of an interface with multiple implementations

Consider a factory like the following:

public interface SomeFactory {
    public SomeValue createSomething(SomeKey key);
}

Furthermore we got some implementation of SomeFactory:

public class SomeFactoryImpl implements SomeFactory {

    @Override
    public SomeValue createSomething(Key key) {
        // some logic
    }

}

Let us consider a class which wants to use this factory:

public class SomeClass{

@Inject
private SomeFactory someFactory;

    public String someMethod(Key someKey) {
        someFactory.createSomething(someKey);
        // some more logic
    }
}

What is the advantage of using an interface for the factory in this situation? I thought the following:

Let us assume I want to use another implementation for my factory:

public class AnotherFactoryImpl implements SomeFactory {

    @Override
    public SomeValue createSomething(Key key) {
        // some logic
    }

}

Which factory will then be used with the @Inject-annotation? Would it be more appropriate to Inject the implementation itself, or do we always have just one implementation for the factory? Another possible answer: Is it not appropriate to use an interface for the factory?

Upvotes: 2

Views: 1948

Answers (1)

Alexander Rühl
Alexander Rühl

Reputation: 6939

The idea of using an interface is, that you don't care which implementation you have in your hands, but solely using the interface's methods, which are common among all implementations. Don't forget, that you have to use the same method signature, including the same return value when overriding.

The injection mechanism works by name - so since you don't specify the value in @Inject, it looks for an object named someFactory and injects it, which is fine, since it's of type SomeFactory, no matter which implementation is behind. You may as well inject a specific implementation, which depends on your use case if you deal with the common behavior or a specific one. The instance you want to inject, has to be either bound to the scope you are using or there has to be a Producer which creates the object when needed for injection.


Edit: See my comments below for link to CDI usage and an easier architecture for this use case.

Upvotes: 1

Related Questions