It is good to mix dependency injection with factory pattern?
Would like to know if its good to mix dependency injection with the factory patterns ? I would create differents kind of object at runtime and use them where DI is good to inject stuff so it is ok to inject in the fact开发者_开发知识库ory construction such passing connection string or something ?
Thanks.
It's quite common actually. If you need instances of a certain class on demand, you'll inject a factory instead of a specific object. You should be using the container to construct those objects however (if it needs other objects to be constructed), to stay in the pattern and don't create dependencies.
Absolutely! You can even inject objects into your factories!
public class UserFactory
private final UserStore userStore;
@Inject
UserFactory(UserStore userStore) {
this.userStore;
}
// etc
}
public class CreateUserAction implements Action {
private final UserFactory userFactory;
@Inject
CreateUserAction(UserFactory userFactory) {
this.userFactory = userFactory;
}
@Override
void performAction() {
User user = userFactory.newUser().withRandomId().persisted().build();
}
}
精彩评论