Lazy initialization of singletons

As I read John Skeet's article on singles in C #, I began to wonder why we needed lazy initialization in the first place. It seems that the fourth approach from the article should be sufficient, here for reference purposes:

public sealed class Singleton
{
    static readonly Singleton instance=new Singleton();

    // Explicit static constructor to tell C# compiler
    // not to mark type as beforefieldinit
    static Singleton()
    {
    }

    Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            return instance;
        }
    }
}

In rare cases, when you have other static methods on a singlet, lazy initialization can have advantages, but this is not a good design.

So people can enlighten me, why is lazy initialization such a hot thing?

+3
source share
4 answers

, , , - .

, , , singleton.

, , . "", , - .

+4

, , , ( ), , .

, .

, , , , . , ( , ), .

+10

, #, ++:

Singletons , undefined. , , , .

: , , Singleton. , LoadDB, - , . , LoadDB , - , Singleton. undefined, -, .

, , GetInstance(), , , .

, , , , , ( ).

+1

Java DI, , (, spring) beans API, , , , , (- , ), , . ?

, spring lazy-init = "true" (spring ), init-method/destroy-, @PostConstruct, InitializingBean - afterPropertiesSet() spring getInstance()?

The choice is a compromise between testability over reusability outside the spring container.

0
source

Source: https://habr.com/ru/post/1722743/


All Articles