依赖注入 vs 工厂模式 [英] Dependency Injection vs Factory Pattern

查看:41
本文介绍了依赖注入 vs 工厂模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

引用的大多数依赖注入的使用示例,我们也可以使用工厂模式来解决.看起来在使用/设计方面,依赖注入和工厂之间的区别是模糊或细小的.

Most of the examples quoted for usage of Dependency Injection, we can solve using the factory pattern as well. Looks like when it comes to usage/design the difference between dependency injection and factory is blurred or thin.

曾经有人告诉我,它的使用方式会有所不同!

Once someone told me that its how you use it that makes a difference!

我曾经使用 StructureMap 一个 DI 容器来解决一个问题,后来我将它重新设计为使用一个简单的工厂并删除对 StructureMap 的引用.

I once used StructureMap a DI container to solve a problem, later on I redesigned it to work with a simple factory and removed references to StructureMap.

谁能告诉我它们之间有什么区别,在哪里使用什么,这里的最佳做法是什么?

Can anyone tell me what is the difference between them and where to use what, whats the best practice here?

推荐答案

当使用工厂时,您的代码实际上仍然负责创建对象.通过 DI,您可以将该责任外包给与您的代码分开的另一个类或框架.

When using a factory your code is still actually responsible for creating objects. By DI you outsource that responsibility to another class or a framework, which is separate from your code.

这篇关于依赖注入 vs 工厂模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆