Singletons can be great. But it’s important to make sure that the Singleton really is a Singleton, even in a Multi-Threading Environment.
There are multiple possibilities to achieve this and here are my Favorites:
Nice and clean for almost all cases:
public sealed class Singleton
{
static readonly Singleton _instance = new Singleton();
// Don't mark the Class as beforefieldinit
static Singleton() { }
private Singleton() { }
public static Singleton Instance
{
get
{
return _instance;
}
}
}
Full lazy Implementation:
public sealed class Singleton
{
private Singleton() { }
public static Singleton Instance
{
get
{
return Nested.instance;
}
}
private class Nested
{
// Don't mark the Class as beforefieldinit
static Nested() { }
internal static readonly Singleton _instance = new Singleton();
}
}
Many may use this implementation but it has several drawbacks and may not always work as expected (for example doesn’t work with JAVA). So just don’t use it.
BAD CODE:
public sealed class Singleton
{
static Singleton _instance = null;
static readonly object padlock = new object();
private Singleton() { }
public static Singleton Instance
{
get
{
if (_instance == null)
{
lock (padlock)
{
if (_instance==null)
{
_instance = new Singleton();
}
}
}
return _instance;
}
}
}