Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An obvious singleton implementation for .NET?

Tags:

c#

.net

singleton

I was thinking about the classic issue of lazy singleton initialization - the whole matter of the inefficiency of:

if (instance == null)
{
    instance = new Foo();
}
return instance;

Anyone who knows what a Singleton is is familiar with the issue(you only need the if once). It's trivial but irritating.

So, I thought of an alternate solution, at least for .NET(although it should work anywhere that has some equivalent to function pointers:

public class Foo
{
    private delegate Foo FooReturner();

    private static Foo innerFoo;

    private static FooReturner fooReturnHandler = new FooReturner(InitialFooReturner);

    public static Foo Instance
    {
        get
        {
            return fooReturnHandler();
        }
    }
    private static Foo InitialFooReturner()
    {
        innerFoo = new Foo();
        fooReturnHandler = new FooReturner(NewFooReturner); 
        return innerFoo;
    }

    private static Foo NewFooReturner()
    {
        return innerFoo;
    }

}

In short - the Instance returns a delegate method. The delegate is initially set to a method that initializes your instance, then changes the delegate to point at a simple Return method.

Now, I like to think I'm not terrible at my job, but I have no pretensions about being awesome. I have not seen an example of this code anywhere.

Ergo, I come to the conclusion that I am missing something. Something major. Either that the whole problem is too trivial to bother thinking that much about or this does something horrible that will destroy the universe. Or I fail at searching and therefore haven't seen the hundreds of developers using this method. Something, anyway.

I was hoping the good folks here at Stack Overflow could clue me in as to what(leaving aside the controversy on whether one should use a Singleton at all).

EDIT for clarification:

This is not performance code(although if the design actively degrades performance beyond the traditional model, that would be interesting to know).

It was written purely as proof-of-concept, and I am further aware that it is not thread-safe as it properly should be. Is there any reason why it could NOT be made thread-safe by it's very nature?

like image 733
Faqa Avatar asked Jun 04 '09 21:06

Faqa


People also ask

What is Singleton design pattern in .NET with example?

Singleton is a creational design pattern, which ensures that only one object of its kind exists and provides a single point of access to it for any other code. Singleton has almost the same pros and cons as global variables. Although they're super-handy, they break the modularity of your code.

How is singleton pattern implemented C#?

A singleton pattern can be implemented in C# in several ways, and they have the following qualities in common: A static and open method of obtaining the instance's reference. Single constructor with no parameters in the public domain. Holds references to the single newly produced instance in a static variable.

What is Singleton in .NET core?

Singleton Pattern This pattern is one of the creational patterns, and basically, it ensures that only one object of a particular class is created and shared among other members of the system. Singleton class should enable easy access to its only instance to the other classes.


2 Answers

This is the canonical, thread safe, lazy Singleton pattern in C#:

public sealed class Singleton
{
    Singleton(){}
    public static Singleton Instance
    {
        get
        {
            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();
    }
}
like image 80
Randolpho Avatar answered Oct 22 '22 14:10

Randolpho


To prevent from having to copy the singleton code, you could make the type generic, as such:

public abstract class Singleton<T>
    where T: class, new()
{
    public static T Instance
    {
        get { return Nested.instance; }
    }

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

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

public sealed class MyType : Singleton<MyType>
{
}

class Program
{
    static void Main()
    {
        // two usage pattterns are possible:
        Console.WriteLine(
            ReferenceEquals(
                Singleton<MyType>.Instance, 
                MyType.Instance
            )
        );
        Console.ReadLine();
    }
}
like image 20
oɔɯǝɹ Avatar answered Oct 22 '22 13:10

oɔɯǝɹ