依赖注入与工厂设计模式的主要区别是什么?
您能简单解释一下:依赖注入与工厂设计模式的主要区别是什么?
另外:是否可以通过代码示例非常简单地演示差异?
谢谢
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用工厂(或任何其他创建模式),调用者必须知道如何获取对象,并且必须在使用它之前“明确”请求它。
而使用 DI 时,传递所需对象的责任被委托给某个外部(主要是容器)实体,该实体知道如何创建对象(通过读取已定义的配置)并以静默方式将其提供给调用者。
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.
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.
工厂模式通常可用于重复创建具有可能复杂的实例化逻辑的对象实例。这样,您的类知道工厂并请求实例。
就您的类而言,依赖注入进一步完全抽象出实例化逻辑。您的代码需要关心的只是声明它们所需的依赖项,而不必关心它们来自哪里。
有关详细的指南,请参阅控制容器反转和依赖注入模式。
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.
这两种模式都实现了相同的目标,只是使用工厂设计模式时您必须编写代码,而使用 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.