What is static Singleton mode?
Static Singleton Pattern is the Pattern I have summarized in practice. The main problem is that when a dependency is known as a Singleton application in advance, provide access through static cache of this dependency. Of course, there are many solutions to this problem, but this is only one of them.
Implementation Details
Copy codeThe Code is as follows: // <summary>
/// Static Singleton
/// </Summary>
/// <Typeparam name = "TClass"> Singleton type </typeparam>
Public static class Singleton <TClass> where TClass: class, new ()
{
Private static readonly object _ lock = new object ();
Private static TClass _ instance = default (TClass );
/// <Summary>
/// Obtain the singleton instance
/// </Summary>
Public static TClass GetInstance ()
{
Return Instance;
}
/// <Summary>
/// Singleton instance
/// </Summary>
Public static TClass Instance
{
Get
{
If (_ instance = null)
{
Lock (_ lock)
{
If (_ instance = null)
{
_ Instance = new TClass (); // must be public constructor
}
}
}
Return _ instance;
}
}
/// <Summary>
/// Set a singleton instance
/// </Summary>
/// <Param name = "instance"> Singleton instance </param>
Public static void Set (TClass instance)
{
Lock (_ lock)
{
_ Instance = instance;
}
}
/// <Summary>
/// Reset a singleton instance
/// </Summary>
Public static void Reset ()
{
Lock (_ lock)
{
_ Instance = default (TClass );
}
}
}
Application Testing
Copy codeThe Code is as follows: class Program
{
Interface IInterfaceA
{
String GetData ();
}
Class ClassA: IInterfaceA
{
Public string GetData ()
{
Return string. Format ("This is from ClassA with hash [{0}].", this. GetHashCode ());
}
}
Static void Main (string [] args)
{
String data1 = Singleton <ClassA>. GetInstance (). GetData ();
Console. WriteLine (data1 );
String data2 = Singleton <ClassA>. GetInstance (). GetData ();
Console. WriteLine (data2 );
Console. ReadKey ();
}
}
Test Results