Realistic use case for static factory method?

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

    Use javax.swing.BorderFactory as an example of all three points.

    This class is used to make borders for swing objects. These border objects can be easily re-used, and this factory method allows for this. Here is the javadoc. This factory is a great example of all three points:

    • There are multiple static methods with different names like createEmptyBorder() and createEtchedBorder().
    • These methods will return previously created objects when possible. It's quite frequent that the same border would be used throughout an application.
    • Border itself is actually an interface, so all objects created through this factory are actually classes which implement this interface.

提交回复
热议问题