Singleton lazy vs eager instantiation

前端 未结 5 1486
暗喜
暗喜 2020-12-07 18:51

If a singleton is implemented as follows,

class Singleton {
    private static Singleton instance = new Singleton();

    public static Singleton getInstance         


        
5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-07 19:45

    First of all, the singleton pattern is overused. What you really want to do if you want "one of something" is to declare it a singleton in your DI framework of choice. This is effectively a configuration driven eager singleton, and frees up options for injecting mocks to do proper testing.

    Why not lazy load? Unless your class has a massive initialization routine in construction (which I would argue is also an anti-pattern), there is no benefit and lots of drawbacks to lazy loading. You're just adding complexity and possibly breaking your program if it's not done correctly. The correct way (if you must) is to use the Initialization-on-demand holder idiom.

提交回复
热议问题