Do we ever need to prefer constructors over static factory methods? If so, when?

前端 未结 4 1855
暗喜
暗喜 2021-02-07 15:20

I have been reading Effective Java by Joshua Bloch and so far it really lives up to its reputation. The very first item makes a convincing case for

4条回答
  •  猫巷女王i
    2021-02-07 16:05

    I'm in pretty strong agreement with Josh Bloch here, and he makes the case better than I could, but here are a few places where static factories aren't as appropriate:

    • When dependency injection is more sensible; DI systems (certainly Guice) tend to inject things through their constructors. In particular, DI is appropriate when you expect that the parameters of the constructor might change in the future.
    • When you specifically intend for people to write subclasses, and you're providing a skeleton for them to implement.

提交回复
热议问题