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

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

问题描述

大多数引用依赖注入使用的例子,我们也可以解决使用工厂模式。看起来就像使用/设计依赖注入和工厂之间的区别是模糊的或薄的。

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.

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

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