|
This pattern is one of the best known patterns. This pattern allows only a single instance of itself to be created and gives access to this instance. Usually you can create it this way: public class Singleton
{
private Singleton()
{
}
private static Singleton instance = null;
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
public string SayHello()
{
return "Hello";
}
}
public class test
{
public void Main()
{
Console.WriteLine(Singleton.Instance.SayHello());
}
}
But this is not thread safe. Because two threads could check the same if (instance == null) and create two instance of the Singleton class.
As a solution you can create Nested class and create instance of Singleton in it.
public class Singleton
{
private Singleton()
{
}
public static Singleton Instance
{
get
{
return Nested.instance;
}
}
public string SayHello()
{
return "Hello";
}
private class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
}
internal static readonly Singleton instance = new Singleton();
}
}
|