/// <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; } } }
/// <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(); } }
/// <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() { } }