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

前端 未结 6 875
孤城傲影
孤城傲影 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:21

    Singletons are evil. The problems I've seen surrounding it are not about re-use or extendability of a system (although I could see how that could occur), more so that I can't count the number of times i've seen obscure bugs in a system that arise from singletons.

    If you do need to use a singleton, ensure it's scope is extremely narrow, i.e. judiciously limit the number of other objects in your system that know about it.

提交回复
热议问题