依赖注入与工厂设计模式的主要区别是什么?

发布于 2024-12-04 16:22:43 字数 79 浏览 1 评论 0原文

您能简单解释一下:依赖注入与工厂设计模式的主要区别是什么?

另外:是否可以通过代码示例非常简单地演示差异?

谢谢

Can you briefly explain: What mainly differs Dependency Injection from Factory Design pattern?

Additionally: Is it possible to demonstrate the difference very simply by a code example?

Thanks

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

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

发布评论

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

评论(3

不一样的天空 2024-12-11 16:22:43

使用工厂(或任何其他创建模式),调用者必须知道如何获取对象,并且必须在使用它之前“明确”请求它。

Car car = CarFactory.getCarByModel(LUXURY);

而使用 DI 时,传递所需对象的责任被委托给某个外部(主要是容器)实体,该实体知道如何创建对象(通过读取已定义的配置)并以静默方式将其提供给调用者。

Car car = getCar();
void setCar(Car car){..} // container sets the car fromoutside

With Factory (or any other Creation pattern), the caller has to know how to get the object and has to "explicitly" ask for it before consuming it.

Car car = CarFactory.getCarByModel(LUXURY);

Whereas when using DI, the responsibility to pass the desired object is delegated to some external (container mostly) entity which knows how to create the object (by reading the config already defined) and make it available to the caller silently.

Car car = getCar();
void setCar(Car car){..} // container sets the car fromoutside
我最亲爱的 2024-12-11 16:22:43

工厂模式通常可用于重复创建具有可能复杂的实例化逻辑的对象实例。这样,您的类知道工厂并请求实例。

就您的类而言,依赖注入进一步完全抽象出实例化逻辑。您的代码需要关心的只是声明它们所需的依赖项,而不必关心它们来自哪里。

有关详细的指南,请参阅控制容器反转和依赖注入模式

The factory pattern is typically useful to repeatedly create instances of an object with possibly complex instantiation logic. This way, your classes knows of the factory and requests instances.

Dependency injection goes one step further to completely abstract away instantiation logic as far as your classes are concerned. All your code needs to care about is to declare the dependencies they need, without bothering where they come from.

For a nice in-depth guide, see Inversion of Control Containers and the Dependency Injection pattern.

寂寞花火° 2024-12-11 16:22:43

这两种模式都实现了相同的目标,只是使用工厂设计模式时您必须编写代码,而使用 DI 时您可以使用现有的 DI 框架来为您完成这项工作,并且只需配置依赖项即可。使用工厂模式,您必须为您的类编写工厂。

Same goals are achieved with both patterns, it's just that with the factory design pattern you have to write code whereas with DI you use an existing DI framework to do the job for you and simply do the configuration of the dependencies. With the factory pattern you have to write factories for you classes.

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