我有一个看起来像这样的工厂:
public class Factory {
public Client createClient(String url) {
UrlBuilder urlBuilder = new UrlBuilder(url);
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpProcessor processor = new CompressionHttpProcessor();
httpClient.addRequestInterceptor(processor);
httpClient.addResponseInterceptor(processor);
return new Client(httpClient, urlBuilder);
}
}
这样的课程:
public class Facade {
private Factory factory;
private String url;
public Facade(Factory factory) {
this.factory = factory;
}
public void doStuff() {
Client client = factory.createClient(url);
// do stuff with client
}
public void setUrl(String url) {
this.url = url;
}
}
如何正确使用Google Guice来做同样的事情?我尝试过辅助注射,但我不确定如何创建“UrlBuilder”。有人可以帮忙吗?
答案 0 :(得分:0)
Guice减少了对工厂的需求以及在您的工厂中使用新工具 Java代码。
您的factory
代码似乎违反了该原则。
您可能需要重新设计 facade ,以便它通过注入(使用setClient)方法接收client
对象。
答案 1 :(得分:0)
我创建了一个包含URL的Setting类,并执行了此操作:
public MyModule extends AbstractModule {
private final Settings settings;
public MyModule(Settings settings) {
this.settings = settings;
}
// configure
@Provides
private UrlBuilder createUrlBuilder(Settings settings) {
return new UrlBuilder(settings.getUrl());
}
}
它有点起作用,但我不确定我喜欢它。