1.靜態代碼塊
/// <summary>
/// 靜態代碼塊
/// 僅在第一次調用類的任何成員時自動執行
/// </summary>
public class SingletonStatic
{
private static readonly SingletonStatic _instance =null;
static SingletonStatic()
{
_instance = new SingletonStatic();
}
private SingletonStatic()
{
}
public static SingletonStatic Instance
{
get { return _instance; }
}
}
2.內部類
/// <summary>
/// 內部類
/// </summary>
public class SingletonInner
{
private SingletonInner()
{
}
public static SingletonInner Instance
{
get{ return InnerClass.inner; }
}
private class InnerClass
{
internal static readonly SingletonInner inner = new SingletonInner();
}
}
3.Lazy
/// <summary>
/// Lazy單例
/// </summary>
public class SingletonLazy
{
private static readonly SingletonLazy _instance = new Lazy<SingletonLazy>().Value;
private SingletonLazy()
{
}
public SingletonLazy Instance
{
get { return _instance; }
}
}
/// <summary>
/// https://www.cnblogs.com/zhouzl/archive/2019/04/11/10687909.html
/// </summary>
/// <typeparam name="T"></typeparam>
public abstract class Singleton<T> where T : class
{
// 這里采用實現5的方案,實際可采用上述任意一種方案
class Nested
{
// 創建模板類實例,參數2設為true表示支持私有構造函數
internal static readonly T instance = Activator.CreateInstance(typeof(T), true) as T;
}
private static T instance = null;
public static T Instance { get { return Nested.instance; } }
}
class TestSingleton : Singleton<TestSingleton>
{
// 將構造函數私有化,防止外部通過new創建
private TestSingleton() { }
}