Realistic use case for static factory method?

前端 未结 6 962
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-02 17:01

I\'m familiar with the idea and benefits of a static factory method, as described in Joshua Bloch\'s Effective Java:

  • Factory methods have names, so you can have mo
6条回答
  •  轮回少年
    2021-02-02 17:43

    The textbook example of your second point is Integer.valueOf(int) (similar for Boolean, Short, Long, Byte). For parameter values -128 to 127, this method returns a cached instance instead of creating a new Integer. This makes (auto)boxing/unboxing much more performant for typical values.

    You can't do that with new Integer() since the JLS requires that new create a new instance every time it is called.

提交回复
热议问题