類型和註釋單身,我有幾個類實現interface Provider<Communication>
和我使用的吉斯與@Named
註釋根據需要約束他們,例如:檢索使用吉斯
@Singleton
public class Verizon implements Provider<Call> {
...
}
@Singleton
public class TMobile implements Provider<Call> {
...
}
bind (new TypeLiteral<Provider<Call>>() {}).annotatedWith(
Names.named("Verizon")).to(Verizon.class);
bind (new TypeLiteral<Provider<Call>>() {}).annotatedWith(
Names.named("TMobile")).to(TMobile.class);
是否有實施清潔方式一個工廠,是以名作爲參數,如:
public static <C extends Communication> Provider<C> getCallProvider(C communication) {
String providerName = communication.getProviderName();
return [Guice's matching object for type Provider<?> and @Named = providerName];
}
我用注射器嘗試,但吉斯不會採取通用的參數TypeLiteral:
public <C extends Communication> Provider<C> getCommunicationProvider(C communication) {
return injector.getInstance(Key.get(new TypeLiteral<CommunicationProvider<C>>() {},
Names.named(communication.getProvider().getId())));
}
此拋出:
com.google.inject.ConfigurationException: Guice configuration errors:
1) Provider<C> cannot be used as a key; It is not fully specified.
該方法的問題在於工廠必須意識到所有可能的類型 - 另一方面,我試圖儘量保持通用。 – REAPP3R
工廠應該知道,要創建什麼...如果沒有,請使用Reflections-API並使用命名模式來查找具體的實現。但我認爲這比工廠瞭解所有階級更醜陋。 –