Static factory methods vs Instance (normal) constructors?

前端 未结 11 1487
醉梦人生
醉梦人生 2020-12-02 12:16

In a language where both are available, would you prefer to see an instance constructor or a static method that returns an instance?

For example, if you\'re creating

11条回答
  •  忘掉有多难
    2020-12-02 12:45

    Of course, there are several advantages of static factory methods over constructors.

    1. factory methods help us to write flexible code. Whereas constructors made it tightly coupled.
    2. Static factory methods improve the readability since these allow you to create different instances.
    3. You can return a cached object. For example getInstance() in Singleton.

提交回复
热议问题