将依赖注入与工厂模式混合在一起好吗?

发布于 2024-10-16 04:29:22 字数 102 浏览 3 评论 0原文

想知道将依赖注入与工厂模式混合是否好?我会在运行时创建不同类型的对象,并在 DI 适合注入东西的地方使用它们,因此可以在工厂构造中注入,例如传递连接字符串或其他东西?

谢谢。

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 factory construction such passing connection string or something ?

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

自找没趣 2024-10-23 04:29:22

实际上这很常见。如果您需要按需提供某个类的实例,您将注入一个工厂而不是一个特定的对象。但是,您应该使用容器来构造这些对象(如果需要构造其他对象),以保持模式并且不创建依赖项。

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.

情深如许 2024-10-23 04:29:22

绝对地!您甚至可以将对象注入您的工厂!

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();
  }
}

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();
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文