Consider providing static factory methods insteads of constructors

后端 未结 5 1304
清酒与你
清酒与你 2020-12-06 08:38

The normal way for a class to allow a client to obtain an instance is to provide a public contructor. Another way to do that is providing a public static factory method, whi

5条回答
  •  悲&欢浪女
    2020-12-06 09:08

    The only con is more code to write, but it's still there, so you need at least some benefit for having a factory.

    Factory is not required to always return a new object, that's one advantage.

    Factory can instantiate any subclass it wants, that's another.

    In my projects I often add factories just to make my client code look nicer. If you use a static import for the factory method, the call looks nicer than a new expression, especially if the name of class is not particularly concise, which is often the case.

提交回复
热议问题