Builder pattern vs. Dependency Injection (for instance via Guice)

前端 未结 3 538
粉色の甜心
粉色の甜心 2021-02-05 22:22

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 i

3条回答
  •  盖世英雄少女心
    2021-02-05 23:17

    I'm a firm believer in that you don't need to use dependency injection for everything.

    • For a LookupService it would be natural inject a Dictionary such that its implementation can be swapped out by configuration.

    • 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.

    As a guideline, inject what you need to configure, don't automatically inject everything else.


    Consider a static factory (*) when

    • 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

    • 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

    Consider a builder when

    • there are complex parameter choices. E.g., 5 parameters where some are optional.

    (*) 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.

提交回复
热议问题