Java Singleton vs static - is there a real performance benefit?

前端 未结 7 2048
抹茶落季
抹茶落季 2021-02-04 06:46

I am merging a CVS branch and one of the larger changes is the replacement wherever it occurs of a Singleton pattern with abstract classes that have a static initialisation bloc

7条回答
  •  时光取名叫无心
    2021-02-04 07:11

    Static is bad for extensibility since static methods and fields cannot be extended or overridden by subclasses.

    It's also bad for unit tests. Within a unit test you cannot keep the side effects of different tests from spilling over since you cannot control the classloader. Static fields initialized in one unit test will be visible in another, or worse, running tests concurrently will yield unpredictable results.

    Singleton is generally an ok pattern when used sparingly. I prefer to use a DI framework and let that manage my instances for me (possibly within different scopes, as in Guice).

提交回复
热议问题