Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A generic singleton

What do you guys think about this for a generic singleton?

using System;
using System.Reflection;

// Use like this
/*
public class Highlander : Singleton<Highlander>
{
    private Highlander()
    {
        Console.WriteLine("There can be only one...");
    }
}
*/

public class Singleton<T> where T : class
{
    private static T instance;
    private static object initLock = new object();

    public static T GetInstance()
    {
        if (instance == null)
        {
            CreateInstance();
        }

        return instance;
    }

    private static void CreateInstance()
    {
        lock (initLock)
        {
            if (instance == null)
            {
                Type t = typeof(T);

                // Ensure there are no public constructors...
                ConstructorInfo[] ctors = t.GetConstructors();
                if (ctors.Length > 0)
                {
                   throw new InvalidOperationException(String.Format("{0} has at least one accesible ctor making it impossible to enforce singleton behaviour", t.Name));
                }

                // Create an instance via the private constructor
                instance = (T)Activator.CreateInstance(t, true);
            }
        }
    }
}
like image 460
Simon Hughes Avatar asked Dec 19 '08 11:12

Simon Hughes


People also ask

What is generic Singleton?

The Generic Singleton Pattern in C#The generic constraint 'new()' on the type parameter means that the class T will have to provide a public parameterless constructor. This means that any client code will be able to create as many instances of class T as it likes. Thus, this breaks the Singleton pattern.

What is an example of a singleton?

Example. The Singleton pattern ensures that a class has only one instance and provides a global point of access to that instance. It is named after the singleton set, which is defined to be a set containing one element. The office of the President of the United States is a Singleton.

What is a singleton?

A singleton is a class that allows only a single instance of itself to be created and gives access to that created instance. It contains static variables that can accommodate unique and private instances of itself. It is used in scenarios when a user wants to restrict instantiation of a class to only one object.

How many types of Singleton are there?

There are two types of singleton implementations: eager and lazy initialization. They differ in the way they initialize the singleton instance. We must also consider thread-safety in each of them.


2 Answers

Creating a singleton class is just a few lines of code, and with the difficulty of making a generic singleton i always write those lines of code.

public class Singleton
{
    private Singleton() {}
    static Singleton() {}
    private static Singleton _instance = new Singleton();
    public static Singleton Instance { get { return _instance; }}
}

The

private static Singleton _instance = new Singleton();

line removes the need for locking, as a static constructor is thread safe.

like image 151
AndreasN Avatar answered Sep 21 '22 20:09

AndreasN


Well, it isn't really singleton - since you can't control T, there can be as many T instances as you like.

(removed thread-race; noted the double-checked usage)

like image 30
Marc Gravell Avatar answered Sep 24 '22 20:09

Marc Gravell