Introduction to static Singleton Mode

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.