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);
}
}
}
}
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.
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.
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With