构建器模式与依赖注入(例如通过Guice) [英] Builder pattern vs. Dependency Injection (for instance via Guice)
问题描述
我正在开发一个简单的树形结构数据库,我通常通过Builder(Builder模式)设置依赖项或可选设置。现在我不确定何时使用Guice,何时使用Builder模式以及何时使用静态工厂方法而不是构造函数本身。我已经多次阅读过Effective Java,我认为它至少提到了不暴露构造函数的许多优点。是时候重读了; - )
I'm developing a simple tree-structured database and I'm usually setting dependencies or optional settings via a Builder (Builder pattern). Now I'm not sure when to use for instance Guice, when to use the Builder pattern and when to use a static factory method instead of the constructor itself. I've read Effective Java several times and I think it mentions at least a lot of advantages for not exposing the constructor. It's time to reread ;-)
那么,你知道哪些案例可以清楚地区分吗?我不应该暴露构造函数?因此,例如在每种情况下写公共静态Foo getInstance(...){return new Foo(...)}
?
So, do you know of cases which are clearly distinguishable? And shouldn't I expose the constructor? Thus for instance in every case write public static Foo getInstance(...) { return new Foo(...)}
?
推荐答案
我坚信你不需要为一切使用依赖注入。
I'm a firm believer in that you don't need to use dependency injection for everything.
-
对于
LookupService
,这很自然 inject aDictionary
,以便可以通过配置交换其实现。
For a
LookupService
it would be natural inject aDictionary
such that its implementation can be swapped out by configuration.
另一方面,对于防火墙
。它很自然地创建自己的 FireWallRules
,可能是通过提供的 Factory
或生成器
。
For a Firewall
on the other hand. It would be natural for it to create its own FireWallRules
, perhaps through a supplied Factory
or a Builder
.
作为指导,注入 configure 所需的内容,不要自动注入其他一切。
As a guideline, inject what you need to configure, don't automatically inject everything else.
考虑 静态工厂(*)
何时
Consider a static factory (*)
when
- 需要命名构造逻辑。例如,
Lists.newArrayList()
- 构造非常复杂,不属于类本身
- 不需要工厂配置,工厂有没有副作用
- named construction logic is desired. E.g.,
Lists.newArrayList()
- the construction is so complicated it doesn't belong in the class itself
- no configuration of the factory is required, and the factory has no side effects
考虑 实例工厂
何时
Consider instance factories
when
- 复杂实例化逻辑
- 需要工厂配置
- 使用
AbstractFactory
设计模式 - 需要在整个程序生命周期中创建其他对象
- there is complex instantiation logic
- configuration of the factory is needed
- using
AbstractFactory
design pattern - there's need to create additional objects throughout the programs lifecycle
考虑 builder
何时
Consider a builder
when
- 有复杂的参数选择。例如,5个参数,其中一些是可选的。
(*)
静态方法并不总是可测试的,在我看来,一个人的存在总是有动力的。
工厂的典型用例是减少耦合。通过使用静态工厂
,该功能完全丢失。
(*)
Static methods are not always testable and the presence of one should in my opinion always be motivated.
A typical usecase for a factory is to decrease coupling. By using a static factory
that ability is completely lost.
这篇关于构建器模式与依赖注入(例如通过Guice)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!