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

前端 未结 4 1850
暗喜
暗喜 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条回答
  •  醉酒成梦
    2021-02-07 15:51

    static factories still have to call a constructor in the end. You can move most of the functionality into the static factory, but you cannot avoid using a constructor.

    On the other hand for simple cases, you can have just a constructor without having a static factory.

    Constructors are the only way to set final fields, which IMHO are preferable to non-final fields.

    You can use constructors can in sub-classes. You cannot use static factories for a sub-class.

    If you have a good dependency injection framework to build dependencies of a component, you may find that static factories don't add much.

提交回复
热议问题