When to use a Constructor and when to use getInstance() method (static factory methods)?

前端 未结 6 867
孤城傲影
孤城傲影 2020-11-27 10:45
  1. When and how should we use a constructor

    Foo bar = new Foo();
    
  2. And when and how should we use getInstance() (static factory

6条回答
  •  时光取名叫无心
    2020-11-27 11:18

    One case in which I always prefer a static factory over a regular constructor is when I know the object construction will be slowish. I do simple initialization on constructor, but if I need to create something heavy I'll use a static method and document the behavior.

提交回复
热议问题