Realistic use case for static factory method?

前端 未结 6 902
爱一瞬间的悲伤
爱一瞬间的悲伤 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:28

    My current favorite example of this pattern is Guava's ImmutableList. Instances of it can only be created by static factories or a builder. Here are some ways that this is advantageous:

    • Since ImmutableList doesn't expose any public or protected constructors, it can be subclassed within the package while not allowing users to subclass it (and potentially break its immutability guarantee).
    • Given that, its factory methods are all able to return specialized subclasses of it without exposing their types.
    • Its ImmutableList.of() factory method returns a singleton instance of EmptyImmutableList. This demonstrates how a static factory method doesn't need to create a new instance if it doesn't have to.
    • Its ImmutableList.of(E) method returns an instance of SingletonImmutableList which is optimized because it will only ever hold exactly 1 element.
    • Most of its other factory methods return a RegularImmutableList.
    • Its copyOf(Collection) static factory method also does not always need to create a new instance... if the Collection it is given is itself an ImmutableList, it can just return that!

提交回复
热议问题