I want to instantiate an User Account. I can use a factory such as this:
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
Now if I use Google Guice, I must write a "module":
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 .....
}
}
Then, this is client code:
Injector injector = Guice.createInjector(new UserModule().setType(UserType.FREE)));
My question is: Instead of writing a factory class, I have to write a module class. And from the example above, I don't see any advantage. The Module class use reflection, it's slower than my assignment statement in the factory class. The Module class is not any simpler than the factory class. Instead of maintaining the factory, I must maintain the module.
What is the real advantage anyway? Isn't Google Guice just another factory class?