DI容器,工厂或临时性物品的新容器? [英] DI container, factory, or new for ephemeral objects?

查看:85
本文介绍了DI容器,工厂或临时性物品的新容器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在处理仅需要运行时知道数据的对象(例如用户名和密码)时,对象实例化应该在哪里发生:通过在工厂或DI容器中使用new?

例如,一旦获得数据,我就可以new一个对象:

UserCredentials creds =
    new UserCredentials(dialog.getUsername(), dialog.getPassword());

或者,我可以使用工厂:

UserCredentials creds =
    CredentialsFactory.create(dialog.getUsername(), dialog.getPassword());

或者,我可以在DI容器中使用提供程序(在这种情况下,它实际上是一个参数驱动的工厂). [省略了示例代码.]

将DI容器用于如此简单的东西似乎都错了,但是没有充分利用它似乎也错了.

解决方案

一如既往,这要取决于情况,但是作为一般规则,像第二种选择那样的静态工厂很少是一个好主意.

new建立UserCredentials对象似乎是一个公平的选择,因为UserCredentials类看起来像一个独立的具体类,可以使用用户名和密码中的所有不变量来完全实例化.

在其他情况下,您要创建的类型本身可能表示一个抽象.在这种情况下,您不能使用new关键字,而必须使用 Abstract Factory .

使用抽象工厂通常非常有价值,因为它使您可以结合运行时值和其他依赖项来组成实例.有关更多信息,请参见此处.

使用抽象工厂还有助于进行单元测试,因为您可以简单地测试返回值或最终状态或您关心的任何内容与抽象工厂的输出有关-为此,您可以容易提供 Test Double ,因为它是...摘要.

When dealing with objects that require data known only at runtime, such as a username and password, where should object instantiation happen: by using new, in a factory, or in a DI container?

For example, I could just new an object once I have the data:

UserCredentials creds =
    new UserCredentials(dialog.getUsername(), dialog.getPassword());

Or, I could use a factory:

UserCredentials creds =
    CredentialsFactory.create(dialog.getUsername(), dialog.getPassword());

Or, I could use a provider within a DI container (which in this case would essentially be a parameter-driven factory). [Sample code omitted.]

It seems both wrong to use the DI container for something so simple yet it also seems wrong not to use it to its fullest.

解决方案

As always, it depends, but as a general rule, a static factory like your second option is only rarely a good idea.

newing up a UserCredential object seems like a fair choice because the UserCredentials class looks like a self-contained, concrete class that can be fully instantiated with all its invariants from the username and password.

In other cases, the type you would like to create may represent an abstraction in itself. If this is the case, you can't use the new keyword, but must use an Abstract Factory instead.

Using an Abstract Factory is often very valuable because it allows you to compose an instance from a combination of run-time values and other dependencies. See here for more information.

Using an Abstract Factory also helps with unit testing because you can simply test that the return value or end state or whatever you care about is related to the output of the Abstract Factory - for which you can easily supply a Test Double because it is... abstract.

这篇关于DI容器,工厂或临时性物品的新容器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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