我想实例化一个用户帐户.我可以使用这样的工厂:
public class UserFactory {
public User newUser(UserType type) {
if (type == UserType.FREE) return new FreeUser();
}
}
User user = UserFactory.newUser(UserType.FREE); //UserType.FREE is an enum
Run Code Online (Sandbox Code Playgroud)
现在如果我使用Google Guice,我必须写一个"模块":
public class UserModule extends AbstractModule {
public voidSetType(UserType type) {
this.type = type;
}
@Override
protected void configure() {
if (this.type = UserType.FREE)
bind(User.class).to(FreeUser.class);
else bind .....
}
}
Run Code Online (Sandbox Code Playgroud)
然后,这是客户端代码:
Injector injector = Guice.createInjector(new UserModule().setType(UserType.FREE)));
Run Code Online (Sandbox Code Playgroud)
我的问题是:我必须编写一个模块类,而不是编写工厂类.从上面的例子中,我没有看到任何优势.Module类使用反射,它比工厂类中的赋值语句慢.Module类并不比工厂类简单.我必须维护模块,而不是维护工厂.
无论如何,真正的优势是什么?Google Guice不是另一个工厂类吗?