Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
602 views
in Technique[技术] by (71.8m points)

design-patterns - 什么是依赖注入?(What is dependency injection?)

There have been several questions already posted with specific questions about dependency injection , such as when to use it and what frameworks are there for it.

(已经发布了几个问题,其中包含有关依赖项注入的特定问题,例如何时使用它以及支持它的框架。)

However,

(然而,)

What is dependency injection and when/why should or shouldn't it be used?

(什么是依赖项注入?何时/为什么/不应该使用它?)

  ask by AR. translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The best definition I've found so far is one by James Shore :

(到目前为止,我发现的最佳定义是James Shore定义的 :)

"Dependency Injection" is a 25-dollar term for a 5-cent concept.

(“依赖注入”是5美分概念的25美元术语。)

[...] Dependency injection means giving an object its instance variables.

(依赖注入意味着给对象一个实例变量。)

[...].

([...]。)

There is an article by Martin Fowler that may prove useful, too.

(Martin Fowler的一篇文章可能也很有用。)

Dependency injection is basically providing the objects that an object needs (its dependencies) instead of having it construct them itself.

(依赖注入基本上是提供对象需要的对象(其依赖),而不是让对象自己构造它们。)

It's a very useful technique for testing, since it allows dependencies to be mocked or stubbed out.

(这是一种非常有用的测试技术,因为它允许对依赖项进行模拟或存根。)

Dependencies can be injected into objects by many means (such as constructor injection or setter injection).

(可以通过多种方式将依赖项注入到对象中(例如构造函数注入或setter注入)。)

One can even use specialized dependency injection frameworks (eg Spring) to do that, but they certainly aren't required.

(甚至可以使用专门的依赖项注入框架(例如Spring)来做到这一点,但是肯定不是必需的。)

You don't need those frameworks to have dependency injection.

(您不需要那些框架具有依赖项注入。)

Instantiating and passing objects (dependencies) explicitly is just as good an injection as injection by framework.

(显式实例化和传递对象(依赖项)与框架注入一样好。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...