Implementing the Singleton Pattern in C#

Implementing the Singleton Pattern in C#

I’m not interested in threading any more, but I’ve found this article while I was searching for the comments on Visual Blogger 2004. (BTW, everybody hates Visual Blogger cuz it’s too buggy.)

Something interesting in the article:

(1) DCL certainly does not work in .NET either.

(2) fully lazy instantiation


public sealed class Singleton
{
    Singleton()
    {
    }

    public static Singleton GetInstance()
    {
        return Nested.instance;
    }
    
    class Nested
    {
        // Explicit static constructor to tell C# compiler
        // not to mark type as beforefieldinit
        static Nested()
        {
        }

        internal static readonly Singleton instance = new Singleton();
    }
}

Whether this kind of lazy initialization would work is completely depends on the class loading mechanism of virutal machine. (I think this code also will work pretty well in JAVA.)

But, there’s one thing to remeber.

Nested class is declared as ‘private’ rather than ‘private static’ which violates the crucial rule in OOP, ‘Do not give an access unless if you really have to.’

In other words, nested class can access any instance variables within Singleton class, though it need not. I know that this is inevitable to gurantee ‘lazy initailization.’ (If Nested was declared as static, variable instance will be loaded when any thread accesses Singleton class. But the primary intention was not to load instance variable unless GetInstance() is called.)

Anyway, though I’m not Mr. Everything is object, violation of rule is violation of rule…

I’ll give my credit to the following code as the best practice.


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 GetInstance()
    {
        return instance;
    }
}

Similar Posts:

Post a Comment

Your email is never published nor shared.